What is the linq equivalent to the SQL IN operator

2019-01-14 05:25发布

With linq I have to check if a value of a row is present in an array.
The equivalent of the sql query:

WHERE ID IN (2,3,4,5)

How can I do it?

8条回答
来,给爷笑一个
2楼-- · 2019-01-14 05:34
db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x));

or

from x in db.SomeTable
where new[] {2,3,4,5}.Contains(x)
查看更多
贪生不怕死
3楼-- · 2019-01-14 05:40

Perform the equivalent of an SQL IN with IEnumerable.Contains().

var idlist = new int[] { 2, 3, 4, 5 };

var result = from x in source
          where idlist.Contains(x.Id)
          select x;
查看更多
仙女界的扛把子
4楼-- · 2019-01-14 05:43

Following is a generic extension method that can be used to search a value within a list of values:

    public static bool In<T>(this T searchValue, params T[] valuesToSearch)
    {
        if (valuesToSearch == null)
            return false;
        for (int i = 0; i < valuesToSearch.Length; i++)
            if (searchValue.Equals(valuesToSearch[i]))
                return true;

        return false;
    }

This can be used as:

int i = 5;
i.In(45, 44, 5, 234); // Returns true

string s = "test";
s.In("aa", "b", "c"); // Returns false

This is handy in conditional statements.

查看更多
Rolldiameter
5楼-- · 2019-01-14 05:44

.Contains

var resultset = from x in collection where new[] {2,3,4,5}.Contains(x) select x

Of course, with your simple problem, you could have something like:

var resultset = from x in collection where x >= 2 && x <= 5 select x
查看更多
何必那么认真
6楼-- · 2019-01-14 05:47

You can write help-method:

    public bool Contains(int x, params int[] set) {
        return set.Contains(x);
    }

and use short code:

    var resultset = from x in collection
                    where Contains(x, 2, 3, 4, 5)
                    select x;
查看更多
ゆ 、 Hurt°
7楼-- · 2019-01-14 05:49

An IEnumerable<T>.Contains(T) statement should do what you're looking for.

查看更多
登录 后发表回答