How can you handle an IN sub-query with LINQ to SQL?

I am a bit stuck with this. Basically I want to do something like the following SQL query in LINQ to SQL:

SELECT f.* FROM Foo f WHERE f.FooId IN ( SELECT fb.FooId FROM FooBar fb WHERE fb.BarId = 1000 ) 

Any help would be greatly appreciated.

Thank.

+48
sql linq linq-to-sql
Sep 09 '08 at 7:20
source share
9 answers

Have a look in this article . Basically, if you want to get the equivalent of IN, you need to first build an internal query, and then use the Contains () method. Here is my attempt to translate:

 var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId; var result = from f in Foo where innerQuery.Contains(f.FooId) select f; 
+55
Sep 09 '08 at 8:39
source share
— -

General way to implement IN in LINQ to SQL

 var q = from t1 in table1 let t2s = from t2 in table2 where <Conditions for table2> select t2.KeyField where t2s.Contains(t1.KeyField) select t1; 

General way to implement EXISTS in LINQ to SQL

 var q = from t1 in table1 let t2s = from t2 in table2 where <Conditions for table2> select t2.KeyField where t2s.Any(t1.KeyField) select t1; 
+79
09 Sep '08 at 8:51
source share
 from f in Foo where f.FooID == ( FROM fb in FooBar WHERE fb.BarID == 1000 select fb.FooID ) select f; 
+3
Sep 09 '08 at 7:26
source share

Try using two separate steps:

 // create a Dictionary / Set / Collection fids first var fids = (from fb in FooBar where fb.BarID = 1000 select new { fooID = fb.FooID, barID = fb.BarID }) .ToDictionary(x => x.fooID, x => x.barID); from f in Foo where fids.HasKey(f.FooId) select f 
+2
Sep 09 '08 at 7:25
source share

// first create the dictionary first / Set / Collection

Find other articles

 var fids = (from fb in FooBar where fb.BarID = 1000 select new { fooID = fb.FooID, barID = fb.BarID }) .ToDictionary(x => x.fooID, x => x.barID); from f in Foo where fids.HasKey(f.FooId) select f 
+1
Jul 06 '09 at 16:58
source share

try it

 var fooids = from fb in foobar where fb.BarId=1000 select fb.fooID var ff = from f in foo where f.FooID = fooids select f 
0
Sep 09 '08 at 7:34
source share
 var foos = Foo.Where<br> ( f => FooBar.Where(fb.BarId == 1000).Select(fb => fb.FooId).Contains(f.FooId)); 
0
Sep 15 '08 at 18:02
source share

// first create the dictionary first / Set / Collection

Find other articles

 var fids = (from fb in FooBar where fb.BarID = 1000 select new { fooID = fb.FooID, barID = fb.BarID }) .ToDictionary(x => x.fooID, x => x.barID); from f in Foo where fids.HasKey(f.FooId) select f 
0
Jul 06 '09 at 17:21
source share
 from f in foo where f.FooID equals model.FooBar.SingleOrDefault(fBar => fBar.barID = 1000).FooID select new { f.Columns }; 
0
Jan 23 '12 at 7:32
source share



All Articles