2010-06-15 324 views

回答

21

您使用,where <list>.Contains(<item>)

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

或者你可以有一个列表预先定义为这样的: '!'

var ids = {1, 2, 3}; 

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

对于 '不' 的情况下,只需添加'Contains'语句之前的操作符。

+0

你如何处理,如果它在一个列表? IN('a','b','c') – DOK 2010-06-15 17:56:43

+0

@DOK他刚才提到你如何处理它,如果它在列表中。 – Randolpho 2010-06-15 17:57:21

+0

查看我更新的示例。 – 2010-06-15 17:59:05

8

我很困惑你的问题。 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; 
-1

请尝试一下本作SQL不

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();