1

I´m trying do something like this :

Select * from A where id in (Select id_a from B)

But in LINQ

db.A().Join(db.B(), a => a.id, b => b.id_a, (a , b) => new { a, b}).....

I can do a JOIN. Is the best way? Or i have another options?.

I´m using Entity Framework

Thanks

Sebastian
  • 11
  • 1
  • 3
  • Welcome to StackoverFlow. Please [take the tour](https://stackoverflow.com/tour), read about [how to ask good questions](https://stackoverflow.com/help/how-to-ask) and learn about [how to create a Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/mcve). – Gaurang Dave Apr 10 '18 at 08:59
  • I think what you are doing is correct. Hope you are getting result you want – Gaurang Dave Apr 10 '18 at 09:01
  • Are you using EntityFramework? Do `db.A()` and `db.B()` return `IQueryable`? – haim770 Apr 10 '18 at 09:02
  • Yes, i´m using EntityFramework and both return IQueryable. But didn´t work in the examples of below – Sebastian Apr 11 '18 at 14:44

4 Answers4

1

From my SQL to LINQ recipe:

For translating SQL to LINQ query comprehension:

  1. Translate subselects as separately declared variables.
  2. Translate IN to .Contains() and NOT IN to !...Contains(), using literal arrays or array variables for constant lists.
  3. SELECT * must be replaced with select range_variable or for joins, an anonymous object containing all the range variables.

So, for your SQL,

var id_aInB = from b in db.B select b.id_a;
var ans = from a in db.A where id_aInB.Contains(a.id) select a;
NetMage
  • 26,163
  • 3
  • 34
  • 55
0

Using subquery in LINQ lambda

var q = db.A.Where(a=> db.B.Select(b=>b.id_a).toList().Contains(a.Id)).Select(a=>a);
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34
0

In Linq there are many ways to express that. That SQL can also be expressed in different ways and probably the best is to use an EXISTS query instead, like:

Select * from A 
where EXISTS (Select * from B where A.id = B.id_a)

That could be written in Linq as:

db.A.Where( a => db.B.Any( b => a.Id == b.Id_a ) );
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
0

Maybe you need this:

var result=db.A.Select(c=>new {c,listId=db.B.Select(s=>s.id_a)}).Where(w=>w.listId.Contains( w.c.id)).Select(c=>c.c);

Or you can use LINQ like this

from a in db.A
let listId = from b in db.B
select b.id_a
where listId.Contains(a.id)
select a

By the way, use LINQPad,you can get the right lamda by LINQ search

我零0七
  • 315
  • 3
  • 6