Back to results for “Collections”
C# › LINQ

How do GroupBy() and its resulting IGrouping<TKey, TElement> work?

Intermediate

Answer

GroupBy() partitions a sequence into GROUPS based on a key selector, returning a sequence of IGrouping<TKey, TElement> objects — each group acts as both a KEY (accessible via .Key) and an ENUMERABLE of the elements sharing that key, letting you process or aggregate each group independently.
var people = new List<Person> { new("Sam", "IT"), new("Alex", "IT"), new("Jo", "HR") };
var byDept = people.GroupBy(p => p.Department);
foreach (var group in byDept) {
  Console.WriteLine($"{group.Key}: {group.Count()} people");
}
// "IT: 2 people", "HR: 1 people"
Real-world example Grouping a flat list of orders by customer, or employees by department, for a summary report.

Common follow-ups: How would you combine GroupBy() with Select() to produce a summary object (count, average, etc.) for each group?