Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for multiple values in an if statement in C# [duplicate]

Is there a shorthand syntax in C# to make this:

if ((x == 1) || (x==2) || (x==5) || (x==13) || (x==14))

... shorter? Something like (hypothetically)

if (x in {1, 2, 5, 13, 14})

I "feel" like it exists, I'm just coming up short mentally and Googly. In reality I have to test a bunch of enums frequently and it's just unreadable. I also hate to make a little helper function if the language supports it already.

Thanks in advance!

Edit

There are clever solutions involving lists... but I was hoping for a pure logical construct of some kind. If it doesn't exist, so be it. Thanks!

like image 203
Adamlive Avatar asked Mar 07 '12 01:03

Adamlive


2 Answers

Try this:

if ((new[]{1, 2, 5, 13, 14}).Contains(x)) ...
like image 90
Sergey Kalinichenko Avatar answered Sep 20 '22 00:09

Sergey Kalinichenko


Though I think the if statement is fine, and making code brief for breifness's sake is useless, here goes:

First approach, assuming you want to go the LINQ route:

if ((new[]{1,2,5,13,14}).Contains(x)){
}

Second approach, ArrayList

if ((new System.Collections.ArrayList(new[]{1,2,5,13,14})).Contains(x)){
}

Third approach, List:

if ((new System.Collections.Generic.List<Int32>(new[]{1,2,5,13,14})).Contains(x)){
}

But keep in mind all of these add more overhead (and really don't add much as far as readability, given the performance consideration).

oh, and working example of the above.

like image 34
Brad Christie Avatar answered Sep 17 '22 00:09

Brad Christie