2.8 — GroupBy, Join, SelectMany, Aggregate, Zip¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.7 Expression trees · Next: 2.9 First vs Single
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
GroupByturns a flat list into buckets. Each bucket has aKeyand the items in it.Joinmatches items from two sequences by a shared value — exactly like a SQL inner join.SelectManyflattens.Aggregatefolds a sequence into one value.Zippairs two sequences item by item.
The concept¶
These five are where LINQ stops being "a nicer foreach" and starts doing things that would
take real effort by hand. They also come up in interviews because writing one on a whiteboard
shows whether you have used LINQ properly or just Where and Select.
A picture for each:
GroupBy— sorting a pile of post into pigeonholes, one per street name.Join— laying two lists side by side and drawing lines between matching IDs.SelectMany— tipping several boxes of items into one big box.Aggregate— a running total, but you decide what "adding" means.Zip— a zip fastener, pairing one tooth from each side.
How it works¶
GroupBy — split into buckets¶
You get back a sequence of groups. Each group is itself a sequence, plus a Key
property holding the value you grouped by:
foreach (var group in byCustomer)
{
Console.WriteLine($"Customer {group.Key}:"); // the CustomerId
foreach (var order in group) // the orders for that customer
Console.WriteLine($" {order.Id}");
}
That double nature — a group is the items, and has a Key — is the bit people find
confusing. In practice you usually project straight into a summary:
var summaries = orders
.GroupBy(o => o.CustomerId)
.Select(g => new
{
CustomerId = g.Key, // what you grouped by
Count = g.Count(), // g is the orders in this bucket
Total = g.Sum(o => o.Total)
});
Grouping by more than one value uses an anonymous type or a tuple as the key:
var byMonthAndStatus = orders
.GroupBy(o => new { o.CreatedAt.Year, o.CreatedAt.Month, o.Status })
.Select(g => new
{
g.Key.Year, g.Key.Month, g.Key.Status,
Count = g.Count()
});
That works because anonymous types compare by value (1.22) — two keys with the same contents land in the same bucket.
⚠️ GroupBy reads the entire source before it can produce anything. It cannot know
what is in a bucket until it has seen every item. So it is deferred, but not streaming.
Join — match two sequences¶
var result = orders.Join(
customers, // the second sequence
o => o.CustomerId, // key from the first
c => c.Id, // key from the second
(o, c) => new // what to build from each match
{
OrderId = o.Id,
Customer = c.Name,
o.Total
});
Four arguments, in that order: what to join, key from the left, key from the right, what to produce.
This is an inner join — items with no match on either side are dropped.
Query syntax is genuinely more readable here:
var result = from o in orders
join c in customers on o.CustomerId equals c.Id
select new { OrderId = o.Id, Customer = c.Name, o.Total };
For a left join — keep everything from the left even without a match — you use
GroupJoin plus SelectMany with DefaultIfEmpty:
var result = from c in customers
join o in orders on c.Id equals o.CustomerId into customerOrders
from o in customerOrders.DefaultIfEmpty() // ← this makes it a LEFT join
select new
{
Customer = c.Name,
OrderId = o?.Id, // null when the customer has no orders
Total = o?.Total ?? 0
};
That DefaultIfEmpty() is the whole trick, and it is worth memorising because "how do you
do a left join in LINQ?" is a standard question.
SelectMany — flatten¶
// 3 orders, each with 4 lines
orders.Select(o => o.Lines); // IEnumerable<List<OrderLine>> — 3 lists
orders.SelectMany(o => o.Lines); // IEnumerable<OrderLine> — 12 lines
With the overload that keeps the parent, you can reach both:
var lines = orders.SelectMany(
o => o.Lines, // what to flatten
(order, line) => new // combine parent and child
{
order.Id,
line.Product,
line.Quantity
});
Aggregate — fold into one value¶
Sum and Count are specialised aggregations. Aggregate lets you define your own:
// Reimplementing Sum, to show the shape
var total = orders.Aggregate(
0m, // starting value
(running, order) => running + order.Total); // how to fold each item in
A more realistic use — building a string:
var names = customers.Aggregate(
new StringBuilder(),
(sb, c) => sb.Append(c.Name).Append(", "),
sb => sb.ToString().TrimEnd(',', ' ')); // optional final transform
⚠️ But do not use Aggregate where a named operator exists. Sum, Max, Count and
string.Join are clearer and usually faster. Aggregate is for genuinely custom folds — a
running balance with rules, or combining objects in a way no built-in covers.
The empty-sequence trap: the single-argument overload throws on an empty sequence, because it has no starting value to return. Always supply a seed:
new List<int>().Aggregate((a, b) => a + b); // InvalidOperationException
new List<int>().Aggregate(0, (a, b) => a + b); // 0 — fine
Zip — pair two sequences¶
var names = new[] { "Ada", "Grace", "Alan" };
var scores = new[] { 90, 95, 88 };
var paired = names.Zip(scores, (n, s) => $"{n}: {s}");
// "Ada: 90", "Grace: 95", "Alan: 88"
// .NET 6+ can produce tuples with no selector
foreach (var (name, score) in names.Zip(scores))
Console.WriteLine($"{name} scored {score}");
Zip stops at the shorter sequence. Three names and five scores gives three results,
silently. If the lengths should match, check first — otherwise you lose data with no error.
Code¶
A realistic report combining several of these:
public IReadOnlyList<CustomerReport> BuildReport(
IEnumerable<Order> orders,
IEnumerable<Customer> customers)
{
return customers
// Left join: keep customers even if they have never ordered
.GroupJoin(
orders,
c => c.Id,
o => o.CustomerId,
(customer, theirOrders) => new { customer, theirOrders })
.Select(x => new CustomerReport
{
Name = x.customer.Name,
OrderCount = x.theirOrders.Count(),
// Sum over an empty sequence is 0, so no guard needed
TotalSpent = x.theirOrders.Sum(o => o.Total),
// Max WOULD throw on empty, so use the null-safe form
LastOrder = x.theirOrders.Any()
? x.theirOrders.Max(o => o.CreatedAt)
: (DateTime?)null,
// SelectMany to reach the lines inside the orders
ItemsBought = x.theirOrders
.SelectMany(o => o.Lines)
.Sum(l => l.Quantity)
})
.OrderByDescending(r => r.TotalSpent)
.ToList();
}
Note the asymmetry called out in the comments: Sum on an empty sequence returns zero,
but Max and Min and Average throw. That inconsistency catches people constantly, and
it is exactly the kind of detail an interviewer probes.
Interview questions¶
Q: What does GroupBy return?
A sequence of groups, where each group implements IGrouping<TKey, TElement>. That interface
is itself an IEnumerable of the items in the group, plus a Key property holding the value
you grouped by. So a group both is the items and has the key. In practice you almost
always follow it with a Select that projects the key and some aggregate over the group into
a summary object. Worth knowing that GroupBy has to read the whole source before it can
emit anything, since it cannot know what belongs in a bucket otherwise.
Q: How do you do a left join in LINQ?
Join is always an inner join, so unmatched items on either side disappear. For a left join
you use GroupJoin, which gives you each left item together with a collection of its matches
— possibly empty — and then SelectMany with DefaultIfEmpty(), which yields a null for
groups that had no match. In query syntax that is join ... into g followed by
from x in g.DefaultIfEmpty(). The DefaultIfEmpty is the part that actually makes it a
left join.
Q: What is the difference between Select and SelectMany?
Select produces exactly one output per input, so if the thing you project is a collection
you end up with a sequence of collections. SelectMany does the same projection but flattens
the results into a single sequence. With three orders of four lines each, Select gives you
three lists and SelectMany gives you twelve lines. There is also an overload that passes
both the parent and the child to your projection, which is how you keep the order ID alongside
each line.
Q: When would you use Aggregate?
Only when there is no named operator for what you need. Sum, Count, Max and
string.Join are all specialised aggregations and they are clearer and usually faster, so
reaching for Aggregate to reimplement them is a readability regression. It earns its place
for genuinely custom folds — computing a running balance with business rules, or combining
objects in a way nothing built-in covers. The trap is that the overload without a seed throws
on an empty sequence, so I always supply an explicit starting value.
Traps ⚠️¶
Sumreturns 0 on an empty sequence, butMax,MinandAveragethrow. Guard withAny()or use the nullable overloads.Aggregatewithout a seed throws on an empty sequence. Always pass a starting value.Zipsilently stops at the shorter sequence. No error, just missing data.Joinis an inner join. Unmatched items on both sides vanish, which can look like data loss.GroupBybuffers the entire source. It is deferred, but it cannot stream.GroupByin EF Core does not always translate. Complex groupings can fall back or throw; check the generated SQL. See 13.15.- Grouping by a class without value equality puts every item in its own bucket. Use an anonymous type, a tuple, or a record as the key.
- Reusing
AggregatewhereSumexists is slower and harder to read.
Related¶
- 2.5 LINQ basics — the core operators
- 2.6 Deferred execution — why
GroupBybuffers - 2.9 First vs Single — the element operators
- 1.22 Anonymous types — composite group keys
- 14.1 SQL fundamentals — the joins these mirror
- 13.15 Query performance — when these translate to SQL