Is there a C# IN operator?

Paul Michaels picture Paul Michaels · Jul 2, 2010 · Viewed 85.2k times · Source

In SQL, you can use the following syntax:

SELECT *
FROM MY_TABLE
WHERE VALUE_1 IN (1, 2, 3)

Is there an equivalent in C#? The IDE seems to recognise "in" as a keyword, but I don't seem to be able to find any information on it.

So, is it possible to do something like the following:

int myValue = 1;
if (myValue in (1, 2, 3))
    // Do something

Instead of

int myValue = 1;
if (myValue == 1 || myValue == 2 || myValue == 3)
    // Do something

Answer

Andy Robinson picture Andy Robinson · Jul 2, 2010

If you wanted to write .In then you could create an extension that allows you to do that.

static class Extensions
{

    public static bool In<T>(this T item, params T[] items)
    {
        if (items == null)
            throw new ArgumentNullException("items");

        return items.Contains(item);
    }

}


class Program
{

    static void Main()
    {


        int myValue = 1;

        if (myValue.In(1, 2, 3))
            // Do Somthing...

        string ds = "Bob";

        if (ds.In("andy", "joel", "matt")) 
        // Do Someting...
    }
}