Last Updated: December 26, 2018
·
1.443K
· marwan

Use GroupBy method to group objects based on more than one property/field value

It is very common to use the GroupBy method to group objects based on the value of field, property or method returned value.
var groupedByAge = people.GroupBy(p => p.Age);

But you can also group objects based on the value of not just one field but more.
Example:

var people = new[]
{
    new Person
        {
            Name = "Marwan",
            Age = 25,
            JobTitle ="Developer"
        },
    new Person
        {
            Name = "Hamed",
            Age = 24,
            JobTitle ="Designer"
        },
    new Person
        {
            Name = "Atef",
            Age = 24,
            JobTitle ="Designer"
        },
    new Person
        {
            Name = "Khaled",
            Age = 24,
            JobTitle ="DB Admin"
        }
};

var byAge = people.GroupBy(p => p.Age);
foreach (var group in byAge)
{
    Console.WriteLine("Age {0}", group.Key);
    foreach (var person in group)
    {
        Console.WriteLine("\t{0}", person.Name);
    }
}

var byAgeAndJobTitle = people
                      .GroupBy(p => new {
                                       p.Age,
                                       p.JobTitle
                                    });
foreach (var group in byAgeAndJobTitle)
{
    Console.WriteLine("Age {0} and Job Title {1}",
        group.Key.Age, group.Key.JobTitle);
    foreach (var person in group)
    {
        Console.WriteLine("\t{0}", person.Name);
    }
}

Console.Read();