views:

160

answers:

1

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.

+2  A: 
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
how could I return this anonymus type to the method which calls the function with this query?
Ante B.
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
But with such a simple query, you could just store it in a dictionary
Yuriy Faktorovich