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`…
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s