Kamyar
Kamyar

Reputation: 18797

Equivalent of this SQL query in LINQ using Lambda

What is the correct lambda syntax for the following query?

SELECT a.Title, Count(b.Id) FROM a INNER JOIN b on a.Id = b.FK_Id GROUP BY a.Title  

I know how to use join, but don't have any idea how to use aggregate and group by in this situation.
Thank you.

Upvotes: 0

Views: 116

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500145

Looks to me like:

var query = from a in TableA
            join b in TableB on a.Id equals b.FkId
            group b by a.Title into g
            select new { Title = g.Key, Count = g.Count() };

Or in non-query syntax:

var query = TableA.Join(TableB, a => a.Id, b => b.FkId, (a, b) => new { a, b })
                  .GroupBy(z => z.a.Title, z => z.b)
                  .Select(g => new { Title = g.Key, Count = g.Count() });

Upvotes: 3

Related Questions