Linq to Entities简单组查询

时间:2009-08-31 15:46:42

标签: sql linq linq-to-entities

如何编写(简单)LINQ to Entities查询按一些属性对元素进行分组并计算它们?

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

这应该很简单,但我不知道如何写它。

1 个答案:

答案 0 :(得分:4)

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