Check if a variable is in an ad-hoc list of values
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
}
int x = 1;
if((new List<int> {1, 2, 3}).Contains(x))
{
}
If it's in an IEnumerable<T>
, use this:
if (enumerable.Any(n => n == value)) //whatever
Else, here's a short extension method:
public static bool In<T>(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
public static bool In<T>(this T x, params T[] set)
{
return set.Contains(x);
}
...
if (x.In(1, 2, 3))
{ ... }
Required reading: MSDN Extension methods