Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 332
user1854438 Avatar asked May 31 '13 21:05

user1854438


People also ask

How do you check if a variable is in a list in C#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you check if object already exists in a list Python?

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.


3 Answers

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
}
like image 114
Ilya Ivanov Avatar answered Oct 21 '22 08:10

Ilya Ivanov


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

like image 22
Austin Salonen Avatar answered Oct 21 '22 08:10

Austin Salonen


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
like image 14
It'sNotALie. Avatar answered Oct 21 '22 10:10

It'sNotALie.