How to combine || operators in condition statement [duplicate]

Instead of

if (foo == "1" || foo == "5" || foo == "9" ... ) 

I like to combine them similar to the following (which doesn't work):

if (foo == ("1" || "5" || "9" ... ))

Is that possible?


Solution 1:

Unfortunately not, your best bet is to create an extension method

public static bool IsOneOf<T>(this T value, params T[] options)
{
    return options.Contains(value);
}

and you can use it like this:

if (foo.IsOneOf("1", "5", "9"))
{
    ...
}

Being generic, it can be used for any type (int, string etc).

Solution 2:

You cannot do it this way. Instead you can do this:

string[] validValues = new string[] { "1", "5", "9", "whatever" };
if(validValues.Contains(foo))
{
    // do something
}

Solution 3:

One possible option is this:

switch (foo)
{
    case "1":
    case "5":
    case "9":
        // your code here

        break;
}

Another possible option is this:

var vals = new string[] { "1", "5", "9" };
if (vals.Contains(foo))
{
    // your code here
}