2008-12-15 67 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