Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using If "II" to check for multiple possibilities of the same query [duplicate]

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")) { }
like image 424
Kevin Denham Avatar asked Dec 06 '22 04:12

Kevin Denham


2 Answers

Create a collection that holds the different possibilities:

if(new[] {"string1", "string2", "string3" }.Contains(sCheck)) { }
like image 53
Jeroen Vannevel Avatar answered Dec 10 '22 13:12

Jeroen Vannevel


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
}
like image 38
David Pilkington Avatar answered Dec 10 '22 13:12

David Pilkington