Group by in LINQ

By FoxLearn 12/12/2024 1:08:41 AM   41
In LINQ, the GroupBy method is used to group elements of a collection based on a specified key.

The result of a GroupBy operation is a sequence of groups, where each group contains elements that share the same key.

Grouping by a Single Property

For example:

internal class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

internal class Program
{
    static void Main(string[] args)
    {
        var peoples = new List<Person>
            {
                new Person { Name = "Alice", Age = 25 },
                new Person { Name = "Bob", Age = 30 },
                new Person { Name = "Charlie", Age = 25 },
                new Person { Name = "David", Age = 30 },
                new Person { Name = "Eva", Age = 35 }
            };

        var groupedByAge = peoples.GroupBy(p => p.Age);

        foreach (var group in groupedByAge)
        {
            Console.WriteLine($"Age: {group.Key}");
            foreach (var person in group)
                Console.WriteLine($"  Name: {person.Name}");
        }
    }
}

Output:

Age: 25
  Name: Alice
  Name: Charlie
Age: 30
  Name: Bob
  Name: David
Age: 35
  Name: Eva

The GroupBy method groups people by their Age. Each group has a key (the Age), and each group contains all the Person objects that have that Age.

Grouping and Selecting Specific Data

For example:

var groupedByAge = peoples.GroupBy(p => p.Age)
                         .Select(g => new 
                         {
                             Age = g.Key,
                             Count = g.Count(),
                             People = g.ToList()
                         });

foreach (var group in groupedByAge)
{
    Console.WriteLine($"Age: {group.Age}, Count: {group.Count}");
    foreach (var person in group.People)
    {
        Console.WriteLine($"  Name: {person.Name}");
    }
}

Output:

Age: 25, Count: 2
  Name: Alice
  Name: Charlie
Age: 30, Count: 2
  Name: Bob
  Name: David
Age: 35, Count: 1
  Name: Eva

We can also group by a property and select additional information. For example, group people by age and list the count of people in each group:

Grouping with Aggregation

For example:

var groupedByAge = peoples.GroupBy(p => p.Age)
                         .Select(g => new 
                         {
                             Age = g.Key,
                             AverageAge = g.Average(p => p.Age)
                         });

foreach (var group in groupedByAge)
{
    Console.WriteLine($"Age: {group.Age}, Average Age: {group.AverageAge}");
}

Output:

Age: 25, Average Age: 25
Age: 30, Average Age: 30
Age: 35, Average Age: 35

You can also perform aggregation (like counting, summing, etc.) on the elements within each group. For example, let’s say we want to group by age and calculate the average age of people in each group:

Grouping with Multiple Keys

You can also group by multiple keys. For example, group by both Age and Name:

var groupedByAgeAndName = peoples.GroupBy(p => new { p.Age, p.Name });

foreach (var group in groupedByAgeAndName)
{
    Console.WriteLine($"Age: {group.Key.Age}, Name: {group.Key.Name}");
    foreach (var person in group)
    {
        Console.WriteLine($"  Person: {person.Name}");
    }
}

Output:

Age: 25, Name: Alice
  Person: Alice
Age: 30, Name: Bob
  Person: Bob
Age: 25, Name: Charlie
  Person: Charlie
Age: 30, Name: David
  Person: David
Age: 35, Name: Eva
  Person: Eva