admin

Linq to Entities简单组查询

sql

如何编写(简单的)LINQ to Entities查询以按属性将元素分组并对其进行计数?

SELECT answernumber, count(answerID) FROM answers
WHERE questionID = id
GROUB BY answernumber
ORDERBY answernumber;

那应该很简单,但是我不知道怎么写。


阅读 196

收藏
2021-06-07

共1个答案

admin

var query = answers
   .GroupBy(a => a.answernumber, a => a, (k, g) => new {answernumber = k, Count = g.Count()})
   .OrderyBy(i => i.answernumber);

或另一种方式:

var query2 = from a in answers
         group a by a. answernumber into g
         orderby g.Key
         select new { answernumber = g.Key, Count = g.Count() };
2021-06-07