CodeBlanks Logo Icon CodeBlanks

GroupBy

C# course · Advanced · Lesson 25/83

Learn to group elements by key with GroupBy.

Grouping with GroupBy

GroupBy groups the elements of a sequence by a key. The result is IEnumerable<IGrouping<K, T>>; each group has a key (Key) and the set of items that fall under it.

Example: people.GroupBy(p => p.City) yields one group per city. Iterate the groups with foreach and read g.Key and g.Count(). Keys arrive in first-appearance order.

Iterating groups

An IGrouping<K, T> object is both a key and a sequence of items. g.Key gives the key; since g itself is IEnumerable<T>, you reach its items with foreach or Count().

A nested loop also works: the outer loop walks groups, the inner loop walks each group's items. Groups are ordered by first appearance; items keep their order from the source.

Exercise Group people by city

Group the people list below by City using GroupBy. With foreach print each group's key and item count using Console.WriteLine.

Show example solution
" + g.Count().
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Person
{
    public string Name { get; set; }
    public string City { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Ayşe", City = "Istanbul" },
            new Person { Name = "Ali", City = "Istanbul" },
            new Person { Name = "Mehmet", City = "Ankara" }
        };
        var groups = people.GroupBy(p => p.City);
        foreach (var g in groups)
        {
            Console.WriteLine(g.Key + ": " + g.Count());
        }
    }
}

Test yourself

  1. What does GroupBy return?

    • Groups by key
    • A single value
    • A sorted sequence
    • A filtered sequence
    Show answer

    Groups by key — Correct. GroupBy yields an IGrouping per key.

  2. Complete the GroupBy call

    var groups = people.Group____(p => p.City);
    Show answer
    var groups = people.GroupBy(p => p.City);
  3. Match the member to its description

    Key
    Group's key
    Count()
    Group's item count
    GroupBy
    Split by key
    IGrouping<K,T>
    Group contract

All lessons in Advanced