if statements matching multiple values

Any easier way to write this if statement?

if (value==1 || value==2)

For example... in SQL you can say where value in (1,2) instead of where value=1 or value=2.

I'm looking for something that would work with any basic type... string, int, etc.


Solution 1:

How about:

if (new[] {1, 2}.Contains(value))

It's a hack though :)

Or if you don't mind creating your own extension method, you can create the following:

public static bool In<T>(this T obj, params T[] args)
{
    return args.Contains(obj);
}

And you can use it like this:

if (1.In(1, 2))

:)

Solution 2:

A more complicated way :) that emulates SQL's 'IN':

public static class Ext {    
    public static bool In<T>(this T t,params T[] values){
        foreach (T value in values) {
            if (t.Equals(value)) {
                return true;
            }
        }
        return false;
    }
}

if (value.In(1,2)) {
    // ...
}

But go for the standard way, it's more readable.

EDIT: a better solution, according to @Kobi's suggestion:

public static class Ext {    
    public static bool In<T>(this T t,params T[] values){
        return values.Contains(t);
    }
}

Solution 3:

Is this what you are looking for ?

if (new int[] { 1, 2, 3, 4, 5 }.Contains(value))

Solution 4:

C# 9 supports this directly:

if (value is 1 or 2)

however, in many cases: switch might be clearer (especially with more recent switch syntax enhancements). You can see this here, with the if (value is 1 or 2) getting compiled identically to if (value == 1 || value == 2).