Search code examples
sqlentity-frameworklinq-to-entitiescountgroup-by

SQL to Entity Framework Count Group-By


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

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

Solution

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