2010-06-15 21 views

Trả lời

21

Bạn sử dụng, where <list>.Contains(<item>)

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

Hoặc bạn có thể có một danh sách được xác định trước như vậy: '!'

var ids = {1, 2, 3}; 

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

Đối với 'KHÔNG' trường hợp, chỉ cần thêm toán tử trước câu lệnh 'Chứa'.

+0

Làm thế nào để bạn xử lý nếu nó trong một danh sách? IN ('a', 'b', 'c') – DOK

+0

@DOK anh ta vừa đề cập đến cách bạn xử lý nếu nó nằm trong danh sách. – Randolpho

+0

Xem ví dụ được cập nhật của tôi. –

8

Tôi bị nhầm lẫn bởi câu hỏi của bạn. innot in hoạt động trên các trường trong truy vấn, nhưng bạn không chỉ định trường trong truy vấn mẫu của mình. Vì vậy, nó phải được cái gì đó như:

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

hoặc

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

Tương đương những truy vấn trong LINQ to SQL sẽ là một cái gì đó như thế này:

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

và điều này:

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

Hãy Thử này Đối SQL Không TRÊN

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

Hãy Thử này Đối SQL TRÊN

context.Sal_PackageOrItemCapacity.Where(c => c.ProjectCode == projectCode && c.Status == Helper.Active && c.CapacityFor.Contains(isForItemOrPackage)).ToList();