4

This is normally something I can find online pretty easily but I think I'm having trouble wording it so I apologize if this is a duplicate question.

I'm looking for a more concise way to do an IF/OR check for the same query. For example:

if (sCheck == "string1" || sCheck == "string2" || sCheck == "string3")
{
   MessageBox.Show(sCheck + " is one of the three possible strings.");
}

I'm looking for a cleaner more concise way to do the same If/Or. I was hoping something like these would work but of course they don't:

if (sCheck == "string1" || "string2" || "string3") { }

if (sCheck == ("string1" || "string2" || "string3")) { }
Kevin Denham
  • 519
  • 1
  • 6
  • 24

3 Answers3

10

Create a collection that holds the different possibilities:

if(new[] {"string1", "string2", "string3" }.Contains(sCheck)) { }
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
3

You can create a collection of string and then use the Contains method:

List<string> myStrings = new List<string>(){"string1", "string2" , "string3"};
if (myStrings.Contains(sCheck))
{
   //Do Work
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
2

It probably doesn't make much sense here, but in similar situations, switch can be useful:

switch (sCheck)
{
case "string1":
case "string2":
case "string3":
    MessageBox.Show(sCheck + " is one of the three possible strings.");
    break;    
}
svick
  • 236,525
  • 50
  • 385
  • 514