2008-12-15 66 views

回答

7

你可以嘗試:

var yIds = from y in dataContext.Y 
      where ... 
      select y.XId; 

var query = from x in dataContext.X 
      where yIds.Contains(x.Id) 
      select x; 

,我不知道是否會工作雖然 - 任何理由,你爲什麼不想只是做一個,而不是加入?例如:

var query = from x in dataContext.X 
      join y in dataContext.Y.Where(...) on x.Id equals y.Xid 
      select x; 
+2

需要有一個「別人是鍵入完全相同的答案作爲你「在本網站上彈出的狀態:) – 2008-12-15 09:15:19

+1

未加入的原因:如果x與y一起爲1,則加入將給出重複的x。 – 2008-12-15 13:46:37

+0

@DavidB:對。我不知道在最後添加對Distinct()的調用會做什麼... – 2008-12-15 14:55:08

8

要在SQL中執行IN,您需要使用Linq中的Contains函數。

因此,例如:

var query = from x in GetX() 
      where (from y in GetY() select y.xID).Contains(x.xID) 
      select x; 

你也可以定義內LINQ查詢seperately如果你喜歡,這是更具可讀性

5

我一直在尋找一個NOT IN解決方案的LINQ to SQL一點。由於這個問題,我能夠谷歌正確的事情,發現這個博客帖子:The NOT IN clause in LINQ to SQL

C#

NorthwindDataContext dc = new NorthwindDataContext(); 
var query = 
    from c in dc.Customers 
    where !(from o in dc.Orders 
      select o.CustomerID) 
      .Contains(c.CustomerID) 
    select c; 

VB.net

Dim db As New NorthwinDataContext() 
Dim query = From c In dc.Customers _ 
      Where Not (From o in dc.Orders _ 
         Select o.CustomerID).Contains(c.CustomerID) _ 
      Select c