user1854438 user1854438 - 1 year ago 70
C# Question

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

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(,2,3)) // do something

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download