Is there a shorter way of writing something like this:
if(x==1 || x==2 || x==3) // do something
What I'm looking for is something like this:
if(x.in((1,2,3)) // do something
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
To check if the item exists in the list, use Python “in operator”. For example, we can use the “in” operator with the if condition, and if the item exists in the list, then the condition returns True, and if not, then it returns False.
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
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With