views:

1970

answers:

2

Can anyone tell me how to write a nested SQL query like

SELECT * FROM X WHERE X.ID IN (SELECT Y.XID FROM Y WHERE .....)

in LINQ?

+3  A: 

You could try:

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;

I don't know whether it will work though - any reason why you don't want to just do a join instead? For instance:

var query = from x in dataContext.X
            join y in dataContext.Y.Where(...) on x.Id equals y.Xid
            select x;
Jon Skeet
There needs to be a "someone else is typing exactly the same answer as you" status popup on this site :)
Ch00k
Reason to not join: If x is 1 to many with y, the join will give duplicated x's.
David B
@DavidB: True. I wonder what adding a call to Distinct() at the end would do...
Jon Skeet
+5  A: 

To do an IN in sql, you need to use the Contains function in Linq.

So for example:

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

You could also define the inner linq query seperately if you like, which is a bit more readable

Ch00k