Search code examples
linqjoinlinq-group

Linq joins and groups


Following on from my previous question: Simple inner join in linq

How would I write some linq to do exactly the same as the below..

SELECT A.name, B.name
FROM A
INNER JOIN B ON A.id = B.AID 
INNER JOIN C ON B.id = C.BID
GROUP BY A.Name, B.Name
ORDER BY A.Name

I've tried this but it generates nested selects and thus produces a different number of rows.

var r = from a in db.A
join b in db.B on a.Id equals b.AId
join c in db.C on b.Id equals c.BId
group c by c.B into g1
group b by g1.Key.A into g2
select g2.Key;

I need a group of A's that contains a list of B's which contains a list of C's


Solution

  • Bah my comment lost its formatting

    you can use a let binding in a linq statement to hold a value.

    from a in db.a
    let g1 = a.GroupBy(x => x.Id)
    from item in g1
    let g2 = item.GroupdBy(x => x.Id)
    from item2 in g2
    select new {A = a, B = item, C = item2}
    

    or something like that, hopefully it gives you enough to work it out