Search code examples
c#listpropertieslinq-group

Group List<Person> by properties and get number of times grouped


Lets say I have a class called Person:

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

And a list of persons:

Person { Age = 20, FirstName = "John", LastName = "Joe" }
Person { Age = 20, FirstName = "John", LastName = "Joe" }
Person { Age = 10, FirstName = "James", LastName = "Dokes" }

What I want to have is a (new or old with a new property) list that groups the person by age, first name and last name AND I also want to know how many times that object has been grouped.

So the result of the above would be:

Person { Age = 20, FirstName = "John", LastName = "Joe", Count = 2 }
Person { Age = 10, FirstName = "James", LastName = "Dokes", Count = 1 }

Solution

  • Simple:

    people.GroupBy(x => new { x.Age, x.FirstName, x.LastName })
          .Select(x => new { x.Key.Age, x.Key.FirstName, x.Key.LastName, Count = x.Count() });