6

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!

Adamlive
  • 139
  • 1
  • 2
  • 9
  • http://stackoverflow.com/questions/3907299/c-sharp-if-statements-matching-multiple-values – Jeremy D Mar 07 '12 at 01:43
  • It is not necessary to use inner quotes: `if ( x == 1 || x == 2 || x == 5...)` except if you have used Pascal/Delphi several years and has "professional distortion". – i486 Nov 20 '15 at 10:36

5 Answers5

13

Try this:

if ((new[]{1, 2, 5, 13, 14}).Contains(x)) ...
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
2

I would like to recommend using HashSet(T) Class to check whether the element belongs to the set of elements.

Furthermore, as HashSet<T> is an associative container, its lookup complexity is O(1), i.e. constant time: HashSet(Of T).Contains Method, while Array and List<T> has linear time lookup: O(n). So, HashSet<T> would be the better for lookup.

HashSet<int> numbers = new HashSet<int> { 1, 2, 5, 13, 14 };
int x = 1;
if (numbers.Contains(x))
{
    Console.WriteLine("Contains!");
}
0

No, there is no support for comparing directly like that. However, you could use LINQ methods such as Contains(). I could provide an example but it sort of depends how the data items are originally stored.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

You could perhaps do something like this:

if( Array.LastIndexOf(new int[]{1, 2,3,4}, x) != -1)
{
    //YOUR CODE HERE
}

Not tested, but I believe this would work.

edit Looks like a similar response has already been posted.

A.Midlash
  • 143
  • 4