Trumpster Trumpster - 1 year ago 49
SQL Question

How to group by multiple fields and get the count of another field

So let's say I have a simple class like

class Person
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

and I have an
. What I'm trying to do is the equivalent of

COUNT(Age) As AgeCount
FROM dbo.Persons
GROUP BY FirstName, LastName

if we were in SQL land. How do I write this in LINQ?

I've looked at posts like linq with groupby and count and none of them are exactly like my scenario.

Answer Source

You can group by an anonymous object, then project each group to select the desired properties:

var result = persons
    .GroupBy(p => new { p.FirstName, p.LastName })
    .Select(g => new 
        FirstName = g.Key.FirstName,
        LastName = g.Key.LastName,
        AgeCount = g.Count()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download