2

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

4
  • Welcome to StackoverFlow. Please take the tour, read about how to ask good questions and learn about how to create a Minimal, Complete and Verifiable Example. Commented Apr 10, 2018 at 8:59
  • I think what you are doing is correct. Hope you are getting result you want Commented Apr 10, 2018 at 9:01
  • Are you using EntityFramework? Do db.A() and db.B() return IQueryable? Commented Apr 10, 2018 at 9:02
  • Yes, i´m using EntityFramework and both return IQueryable. But didn´t work in the examples of below Commented Apr 11, 2018 at 14:44

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

Don't use ToList when using LINQ to SQL. Don't do worthless Select(a => a).
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 ) );

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.