For headcount per department in C# LINQ, how do GroupBy, ToLookup and .NET 9's CountBy differ in what they return and when they run?
answer
- groups, an index, or counts
- deferred versus immediate
- IGrouping versus ILookup
- KeyValuePair without the elements
basics
~20 sGroupBy is deferred and yields IGrouping<TKey, TElement> groups each time it is enumerated. ToLookup runs at once and returns an ILookup you can index by key. CountBy, added in .NET 9, yields only KeyValuePair<TKey, int> counts, without building groups.
solid answer
~40 s`GroupBy(e => e.Dept)` returns a deferred sequence of `IGrouping<string, Employee>`; each `IGrouping` has a `Key` and is itself the employees in that group. Nothing runs until you enumerate, and each enumeration re-reads the source, so employees added later appear. `ToLookup(e => e.Dept)` does the same grouping immediately and returns an `ILookup<string, Employee>`: a snapshot with an indexer, where `lookup["IT"]` returns an empty sequence instead of throwing. For headcount alone, .NET 9's `CountBy(e => e.Dept)` yields `KeyValuePair<string, int>` pairs and keeps only a counter per key, not every employee, so it allocates less than `GroupBy(...).Select(g => g.Count())`. `AggregateBy`, also .NET 9, generalises it to a per-key accumulator such as total salary.
code
csharp · 29 linesusing System;
using System.Collections.Generic;
using System.Linq;
var staff = new List<Employee>
{
new("Ana", "Payroll", 5200m), new("Ben", "Legal", 4800m), new("Cleo", "Payroll", 6100m),
};
var grouped = staff.GroupBy(e => e.Dept); // deferred
var lookup = staff.ToLookup(e => e.Dept); // runs now
staff.Add(new("Dev", "Payroll", 5000m));
foreach (var g in grouped)
Console.WriteLine($"GroupBy {g.Key}: {g.Count()}"); // Payroll: 3, Legal: 1
foreach (var g in lookup)
Console.WriteLine($"ToLookup {g.Key}: {g.Count()}"); // Payroll: 2, Legal: 1
Console.WriteLine(lookup["IT"].Count()); // 0, no exception
Console.WriteLine(lookup.Contains("IT")); // False
foreach (var (dept, count) in staff.CountBy(e => e.Dept)) // .NET 9+
Console.WriteLine($"CountBy {dept}: {count}");
var payroll = staff.AggregateBy(e => e.Dept, 0m, (sum, e) => sum + e.Salary); // .NET 9+
Console.WriteLine(string.Join(", ", payroll));
record Employee(string Name, string Dept, decimal Salary);go deeper
Recall that GroupBy produces groups with a Key, and that a group can be counted. Know ToLookup gives something you can index by key.
Contrast deferred GroupBy with immediate ToLookup, explain IGrouping and ILookup, the empty result for a missing lookup key, and what CountBy and AggregateBy save from .NET 9.
Pick the operator by access pattern and allocation: a snapshot lookup for repeated access, CountBy for big counts, and guard against null keys before counting.
Weigh adopting .NET 9 LINQ additions against teams that still target older runtimes, and agree when grouping belongs in memory versus in the data store.
## Three ways to group the same data An HR list of employees, each with a department, must answer "headcount per department". LINQ to Objects offers three operators on `System.Linq.Enumerable`, and they differ in **what they return** and **when they run**. | Operator | Returns | Runs | Keeps the elements | |---|---|---|---| | `GroupBy` | `IEnumerable<IGrouping<TKey, TElement>>` | deferred, on each enumeration | yes | | `ToLookup` | `ILookup<TKey, TElement>` | immediately, once | yes | | `CountBy` (.NET 9) | `IEnumerable<KeyValuePair<TKey, int>>` | deferred | no, only a count | | `AggregateBy` (.NET 9) | `IEnumerable<KeyValuePair<TKey, TAccumulate>>` | deferred | no, only the accumulator | ## GroupBy: deferred groups `GroupBy` returns a query object. Nothing is read until you start a `foreach`. On the first `MoveNext` it reads the **whole** source into an internal lookup, because it cannot know a group is complete until the source ends, and then yields one `IGrouping<TKey, TElement>` per key. An `IGrouping` has a `Key` property and is itself an `IEnumerable<TElement>`, so `g.Count()` counts the employees in that department. Two properties of the runtime's implementation are useful: - groups come out in the order their key **first appears** in the source, and elements inside a group keep their source order; - a `null` key is allowed and forms its own group. Because it is deferred, enumerating the same `GroupBy` query twice groups the data twice, and an employee added to the list in between shows up in the second pass. Why that happens in general belongs to deferred execution; here it is the line between `GroupBy` and `ToLookup`. ## ToLookup: an immediate, indexable snapshot `ToLookup` performs the same grouping **at the call** and returns an `ILookup<TKey, TElement>`: - the indexer `lookup[key]` returns that key's elements, and for a key that is not present it returns an **empty sequence** rather than throwing, unlike a `Dictionary` indexer; - `Contains(key)` and `Count` (the number of keys) are available; - the lookup is a snapshot: adding an employee to the source list afterwards does not change it. Use it when you will look groups up by key repeatedly, for example finding a department's staff for each row of another report. ## CountBy and AggregateBy: counts without groups Before .NET 9 the idiom was `staff.GroupBy(e => e.Dept).Select(g => new { g.Key, Count = g.Count() })`. It works, but `GroupBy` stores every employee in a group just so they can be counted. .NET 9 added: 1. `CountBy(keySelector)`, which keeps a `Dictionary<TKey, int>` of counters and yields `KeyValuePair<TKey, int>`; 2. `AggregateBy(keySelector, seed, func)`, which keeps one accumulator per key, so total salary per department is `AggregateBy(e => e.Dept, 0m, (sum, e) => sum + e.Salary)`. Both declare `where TKey : notnull`. A `null` key that slips through at run time makes enumeration throw `ArgumentNullException`, whereas `GroupBy` would have formed a `null` group. Both are deferred: the dictionary is built when you start enumerating. The order of the pairs is the dictionary's enumeration order, which is not documented, so sort the result if a report needs a stable order. ## Choosing - Need each department's employees once, in a loop: `GroupBy`. - Need to look departments up by key many times, or need a fixed snapshot: `ToLookup`. - Need only counts or a per-key total on .NET 9 or later: `CountBy` or `AggregateBy`. - Need the result as a `Dictionary`: `CountBy(...).ToDictionary()` or `ToLookup` depending on whether the elements are needed. ## Mistakes interviewers listen for - Saying `GroupBy` returns a `Dictionary`; it returns a sequence of groups. - Expecting `lookup["IT"]` to throw `KeyNotFoundException` when the department has no staff. - Thinking `GroupBy` streams like `Where`; it buffers the whole source before the first group appears. - Using `GroupBy` plus `Count()` for a large dataset on .NET 9 or later when `CountBy` does the job without storing the elements.
- Why does GroupBy appear in lists of buffering operators even though it is deferred?Deferred means it does nothing until enumerated; buffering describes what happens then. On the first `MoveNext`, `GroupBy` must read the entire source to know every member of the first group, so it builds all the groups before yielding one. A `Take(1)` after it still reads the whole source. `Where` and `Select` stream instead, handling one element at a time.
- What happens when CountBy meets an employee whose department is null?`CountBy` declares `where TKey : notnull`, so nullable analysis warns about a `string?` key, and at run time the internal `Dictionary<TKey, int>` rejects the null key: enumeration throws `ArgumentNullException`. `GroupBy` and `ToLookup` accept a `null` key and give it its own group. Map nulls to a placeholder such as `"(unassigned)"` in the key selector before counting.
GroupBy is asking a clerk to sort today's in-tray into piles by department every time you want to look; ToLookup is a printed index made once this morning, where a department nobody filed under simply has a blank entry; CountBy is a tally sheet that records only how many forms each department sent.
- GroupBy returns a Dictionary of department to employees
- ToLookup throws KeyNotFoundException for a missing department
- GroupBy streams one group at a time without reading the whole list
- A ToLookup result reflects employees added to the list later
- CountBy has been in LINQ since .NET Framework 3.5
Assumes .NET 10; CountBy and AggregateBy were added in .NET 9, while GroupBy and ToLookup exist in every supported release.