SQL to Entity Framework Count Group-By

fefwfefefwfwe picture fefwfefefwfwe · Jul 19, 2012 · Viewed 121.1k times · Source

I need to translate this SQL statement to a Linq-Entity query...

SELECT name, count(name) FROM people
GROUP by name

Answer

Aducci picture Aducci · Jul 19, 2012

Query syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });