Check if a variable is in an ad-hoc list of values

user1854438 picture user1854438 · May 31, 2013 · Viewed 32.5k times · Source

Is there a shorter way of writing something like this:

if(x==1 || x==2 || x==3) // do something

What I'm looking for is something like this:

if(x.in((1,2,3)) // do something

Answer

Ilya Ivanov picture Ilya Ivanov · May 31, 2013

You could achieve this by using the List.Contains method:

if(new []{1, 2, 3}.Contains(x))
{
    //x is either 1 or 2 or 3
}