Is there any compare operator in c# like SQL's IN statement

.net, asp.net, c#, sql

Solution

tickets.Where(t => new[] {"Open",
                          "Active",
                          "Reopen",
                          "InActive"}.Any(x => x == t.status))

You can also use the Contain method instead of the Any method, but use the Any method if there's any comparement logic you would like to implement, instead of the default equality comparer.

OR

Implement extensions to support IN method:

public static class Extensions
{
    public static bool In<TItem>(this TItem source, Func<TItem, TItem, bool> comparer, IEnumerable<TItem> items)
    {
        return items.Any(item => comparer(source, item));
    }

    public static bool In<TItem, T>(this TItem source, Func<TItem, T> selector, IEnumerable<TItem> items)
    {
        return items.Select(selector).Contains(selector(source));
    }

    public static bool In<T>(this T source, IEnumerable<T> items)
    {
        return items.Contains(source);
    }

    public static bool In<TItem>(this TItem source, Func<TItem, TItem, bool> comparer, params TItem[] items)
    {
        return source.In(comparer, (IEnumerable<TItem>)items);
    }

    public static bool In<TItem, T>(this TItem source, Func<TItem, T> selector, params TItem[] items)
    {
        return source.In(selector, (IEnumerable<TItem>)items);
    }

    public static bool In<T>(this T source, params T[] items)
    {
        return source.In((IEnumerable<T>)items);
    }
}

And use like this:

bool b;

b = 7.In(3, 5, 6, 7, 8); // true
b = "hi".In("", "10", "hi", "Hello"); // true
b = "hi".In("", "10", "Hi", "Hello"); // false
b = "hi".In((s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase), "", "10", "Hi"); // true

var tuples = new List<Tuple<int, string>>();

for (var i = 0; i < 10; i++)
{
    tuples.Add(Tuple.Create(i, ""));
}

var tuple = Tuple.Create(3, "");

b = tuple.In(tup => tup.Item1, tuples); // true

Problem

This is not a specific question but a generic question which was in my mind from long time I have to check one variable if it contains a value from a list of strings for e.g. ``` status == "Open" || status =="Active" || status =="Reopen" || status = "InActive" etc.. ``` In SQL it is very easy to write this kind of statements e.g. select * from ticket where status in ("Open","Active","Reopen","InActive) I wonder we don't have such easy statement in C#? Do anybody know any easy way like SQL to write this kind of statements without using generic types of if else ,foreach loop or LINQ etc.. I know LINQ is there but still it is not as simple as IN of sql

Original source

Related problems