2010-02-25 22 views
47

用linq我必须检查数组中是否存在一行的值。
SQL查询的等效:相当于SQL IN运算符的linq是什么

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

我该怎么办?

+1

[LINQ中的SQL查询](http://www.codeducky.org/sql-queries-in-linq/#where-in)提供了对LINQ的“WHERE IN”常用SQL操作的翻译。 – 2014-05-28 04:29:51

回答

45

。载

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

当然,你简单的问题,你可以有这样的:

var resultset = from x in collection where x >= 2 && x <= 5 select x 
+0

我收到错误:'int []不包含contains的定义。 – nam 2017-08-14 04:04:57

3

IEnumerable<T>.Contains(T)语句应该做你要找的东西。

9
db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x)); 

from x in db.SomeTable 
where new[] {2,3,4,5}.Contains(x) 
24

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; 
2

一个使用。载有()

List<int> list = new List<int>(); 
for (int k = 1; k < 10; k++) 
{ 
    list.Add(k); 
} 

int[] conditionList = new int[]{2,3,4}; 

var a = (from test in list 
     where conditionList.Contains(test) 
     select test); 
+1

您可以通过将'for'循环更改为'IEnumerable list = Enumerable来清理它。范围(1,10);' – 2010-02-25 13:55:25

+0

采取的点。 +1但公平起见,我只是写代码,我知道会工作,而无需测试它:) – Kamal 2010-02-25 14:05:04

1

你可以写求助方法非常简单的例子:

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

和使用短代码:

var resultset = from x in collection 
        where Contains(x, 2, 3, 4, 5) 
        select x; 
8

相交除了更简洁一些,并且可能性更大你也会快一点。

IN

collection.Intersect(new[] {2,3,4,5}); 

NOT IN

collection.Except(new[] {2,3,4,5}); 

方法的语法在

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

,而不是在

collection.Where(x => !(new[] {2,3,4,5}.Contains(x))); 
0

下面是一个可以用来值的列表中搜索值的通用扩展方法:

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

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

这是有条件的方便:

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; 
    } 

这可以被用来作为声明。