与SQL IN运算符等效的linq是什么

Luc*_*oli 53 sql linq contains

使用linq我必须检查数组中是否存在行的值.
相当于sql查询:

WHERE ID IN (2,3,4,5)
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Dav*_*ton 49

.载

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

当然,有了你的简单问题,你可以得到类似的东西:

var resultset = from x in collection where x >= 2 && x <= 5 select x
Run Code Online (Sandbox Code Playgroud)


Lac*_*che 25

使用IEnumerable.Contains()执行SQL IN的等效操作.

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

var result = from x in source
          where idlist.Contains(x.Id)
          select x;
Run Code Online (Sandbox Code Playgroud)


Jus*_*ner 10

db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x));
Run Code Online (Sandbox Code Playgroud)

要么

from x in db.SomeTable
where new[] {2,3,4,5}.Contains(x)
Run Code Online (Sandbox Code Playgroud)


atr*_*eon 8

Intersect和Except更简洁一点,也可能更快一些.

collection.Intersect(new[] {2,3,4,5});
Run Code Online (Sandbox Code Playgroud)

不在

collection.Except(new[] {2,3,4,5});
Run Code Online (Sandbox Code Playgroud)

要么

IN的方法语法

collection.Where(x => new[] {2,3,4,5}.Contains(x));
Run Code Online (Sandbox Code Playgroud)

而不是

collection.Where(x => !(new[] {2,3,4,5}.Contains(x)));
Run Code Online (Sandbox Code Playgroud)