LINQ to SQL中的in和not in。

13

LINQ to SQL 中,innot in 的含义是什么?

例如:

select * from table in ( ...)
and 
select * from table not in (..)

如何在 LINQ to SQL 中表示与上述语句等价的查询?

3个回答

28

你使用 where <list>.Contains( <item> )

var myProducts = from p in db.Products
                 where productList.Contains(p.ProductID)
                 select p;

或者您可以预定义一个如下的列表:

int[] ids = {1, 2, 3};

var query = from item in context.items
            where ids.Contains( item.id )
            select item;

对于“NOT”情况,只需在“Contains”语句之前添加“!”运算符。


如果它在列表中,您要如何处理? IN('a','b','c') - DOK
@DOK 他刚才提到了如果它在列表中,你会如何处理。 - Randolpho
这个只等于在子句中的作用是什么?它与不在子句中有何区别? - Pranay Rana
请查看我的更新声明,针对“NOT”条件。实际上,您只需要在Contains调用之前添加“!”即可。 - Jordan Parmer
针对.NET版本3.5,请查看https://blogs.msdn.microsoft.com/alexj/2009/03/25/tip-8-how-to-write-where-in-style-queries-using-linq-to-entities/。 - Marcel

8
我对你的问题感到困惑。在查询中,innot in是针对字段进行操作的,但在你的示例查询中没有指定字段。因此应该像这样写:

我对你的问题感到困惑。在查询中,innot in是针对字段进行操作的,但在你的示例查询中没有指定字段。因此应该像这样写:

select * from table where fieldname in ('val1', 'val2')

或者
select * from table where fieldname not in (1, 2)

在 LINQ to SQL 中,相当于那些查询的内容可能是这样的:

List<string> validValues = new List<string>() { "val1", "val2"};
var qry = from item in dataContext.TableName
          where validValues.Contains(item.FieldName)
          select item;

并且这个:

List<int> validValues = new List<int>() { 1, 2};
var qry = from item in dataContext.TableName
          where !validValues.Contains(item.FieldName)
          select item;

0
请尝试以下的SQL Not IN语句:
var v = from cs in context.Sal_Customer
         join sag in context.Sal_SalesAgreement
         on cs.CustomerCode equals sag.CustomerCode
         where
          !(
               from cus in context.Sal_Customer
               join
               cfc in context.Sal_CollectionFromCustomers
               on cus.CustomerCode equals cfc.CustomerCode
               where cus.UnitCode == locationCode &&
                     cus.Status == Helper.Active &&
                     cfc.CollectionType == Helper.CollectionTypeDRF
               select cus.CustomerCode
           ).Contains(cs.CustomerCode) &&
           cs.UnitCode == locationCode &&
           cs.Status == customerStatus &&
           SqlFunctions.DateDiff("Month", sag.AgreementDate, drfaDate) < 36
           select new CustomerDisasterRecoveryDetails
           {
             CustomerCode = cs.CustomerCode,
             CustomerName = cs.CustomerName,
             AgreementDate = sag.AgreementDate,
             AgreementDuration = SqlFunctions.DateDiff("Month", sag.AgreementDate, drfaDate)
   };

请尝试使用SQL IN
context.Sal_PackageOrItemCapacity.Where(c => c.ProjectCode == projectCode && c.Status == Helper.Active && c.CapacityFor.Contains(isForItemOrPackage)).ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接