Linq查询计数和分组

3

有人能告诉我如何在Linq中进行这个SQL查询吗?

SELECT [id], COUNT(*) FROM [data].[dbo].[MyTable] GROUP BY [id]
2个回答

5
您可以尝试以下方法:

您可以尝试以下方法:

 var res = ctx.MyTable  // Start with your table
    .GroupBy(r => r.id) / Group by the key of your choice
    .Select( g => new {Id = g.Key, Count = g.Count()}) // Create an anonymous type w/results
    .ToList(); // Convert the results to List

谢谢。如何按计数排序? - Luís Jesus
@pirezas 在 SelectToList 之间添加 .OrderBy(v => v.Count) - Sergey Kalinichenko

2

你可以尝试这个

var res = from r in MyTable 
          group p by r.id into grouped
          select new {id = g.key, total = g.Count()};

然后,当你需要使用它时,只需执行 ToList()。 你也可以在 select new 之后执行。 我这里没有 Visual Studio 2010 来尝试,但我认为它会起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接