Test for multiple values ​​in if statement in C #

Is there a shorthand syntax in C # to do 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 as if it exists, I just mentally approached thoughts and Googly. In fact, I often have to check a bunch of listings, and this is just unreadable. I also hate doing a little helper function if the language already supports it.

Thanks in advance!

Edit

There are smart solutions containing lists ... but I was hoping for some kind of clean logical construction. If this does not exist, so be it. Thank!

+5
source share
5 answers

Try the following:

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

, if , , :

, LINQ:

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

, ArrayList

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

, :

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

, ( , , ).

oh .

+2

HashSet (T), , .

, HashSet<T> , O (1), : HashSet (Of T).Contains Method, Array List<T> : O (n). , HashSet<T> .

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

, . LINQ, Contains(). , , .

0

, - :

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

, , .

, .

0

All Articles