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

后端 未结 7 1215

Is there a shorter way of writing something like this:

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

Wha

7条回答
  •  悲哀的现实
    2020-12-08 18:51

    If it's in an IEnumerable, use this:

    if (enumerable.Any(n => n == value)) //whatever
    

    Else, here's a short extension method:

    public static bool In(this T value, params T[] input)
    {
        return input.Any(n => object.Equals(n, value));
    } 
    

    Put it in a static class, and you can use it like this:

    if (x.In(1,2,3)) //whatever
    

提交回复
热议问题