2

How to write (simple) LINQ to Entities query that groups elements by some attribut and count them?

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

That should be simple but i don't know how to write it.

Ante
  • 8,567
  • 17
  • 58
  • 70

1 Answers1

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

Or the other way:

var query2 = from a in answers
         group a by a. answernumber into g
         orderby g.Key
         select new { answernumber = g.Key, Count = g.Count() };
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • how could I return this anonymus type to the method which calls the function with this query? – Ante Aug 31 '09 at 16:32
  • Use: http://stackoverflow.com/questions/1070526/how-to-return-anonymous-type-from-c-method-that-uses-linq-to-sql, but if you want to screw with your co-workers use: http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx – Yuriy Faktorovich Aug 31 '09 at 16:47
  • But with such a simple query, you could just store it in a dictionary – Yuriy Faktorovich Aug 31 '09 at 16:56