使用Lambda在LINQ中等效此SQL查询

时间:2011-09-22 11:09:31

标签: sql sql-server linq lambda

以下查询的正确lambda语法是什么?

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

我知道如何使用join,但在这种情况下不知道如何使用aggregate和group by 谢谢。

1 个答案:

答案 0 :(得分:3)

在我看来:

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

或者使用非查询语法:

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