2010-06-15 221 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();