Cybercrux

Everything is achievable through technology

String Contains Switch

If you just want to use switch/case, you can do somethign like this, pseudocode:

string message = “test of mine”;
string[] keys = new string[] {“test2”, “test” };

string sKeyResult = keys.FirstOrDefault(s=>message.Contains(s));

switch (sKeyResult)
{
case “test”:
Console.WriteLine(“yes”);
break;
case “test2”:
Console.WriteLine(“yes for test2”);
break;
}
But if the quantity of keys is a big, you can just replace it with dictionary, like this:

static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
string message = “test of mine”;

// this happens only once, during intialization, this is just sample code
dict.Add(“test”, “yes”);
dict.Add(“test2”, “yes2”);

string sKeyResult = dict.Keys.FirstOrDefault(s=>message.Contains(s));

Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`…
}

Leave a comment