有人能告诉我如何在Linq中进行这个SQL查询吗?
SELECT [id], COUNT(*) FROM [data].[dbo].[MyTable] GROUP BY [id]
您可以尝试以下方法:
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
你可以尝试这个
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
来尝试,但我认为它会起作用。
Select
和ToList
之间添加.OrderBy(v => v.Count)
。 - Sergey Kalinichenko