0

I have a statement similar to this that I need to run in Linq. I started down the road of using .Contains, and can get the first tier to work, but cannot seem to grasp what I need to do to get additional tiers.

Here's the SQL statement:

select * 
from aTable
where aTableId in
    (select aTableId from bTable
    where bTableId in 
        (select bTableId from cTable
        where cTableId in
            (select cTableId from dTable
            where dField = 'a guid'
            )
        )
    )

1 Answer 1

3

Well, the simplest translation would be:

var query = from a in aTable
            where (from b in bTable
                   where (from c in cTable
                          where (from d in dTable
                                 where dField == "a guid"
                                 select d.cTableId)
                                .Contains(c.cTableId)
                          select c.bTableId)
                         .Contains(b.bTableId)
                   select b.aTableId)
                   .Contains(a.aTableId)
            select a;

However, it's likely that a join would be significantly simpler:

var query = from a in aTable
            join b in bTable on a.aTableId equals b.aTableId
            join c in cTable on b.bTableId equals c.bTableId
            join d in dTable on c.cTableId equals d.cTableId
            where d.dField == "a guid"
            select a;

I haven't checked, but I think they'll do the same thing...

Sign up to request clarification or add additional context in comments.

2 Comments

That's what i needed. The only addition was to define the type in the .Contains statements. ie: .Contains((Guid) a.aTableId)
and yes, although the SQL is different for both of these options, the Execution Plan is identical. The second option using Joins is a much more readable solution.

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.