SkillPilotAI

LINQ deep dive

Real data never sits in one list: customers live in one place and orders in another. This deep dive covers combining lists with Join and the .NET 10 LeftJoin, building per-key reports with GroupBy, and the aggregates, SelectMany and Chunk operators you use in every real report.

31.1 Why is it used?

  • Reports need data from two collections (customers + orders), joined on a key such as CustomerId.
  • Business questions are per-key: orders and total spend per customer, count per city.
  • Nested data (a cart with many items) has to be flattened into one list.
  • Large lists often have to be sent in fixed-size batches (an SMS API that takes 4 orders at a time).
  • LINQ does all this declaratively; hand-written loops for joins and grouping are where bugs creep in.

31.2 Sample data

An online shop: three customers and four orders. Neha (Id 3) has no orders yet; that is the detail that causes the bug.

C#
Customer[] customers = [    new(1, "Aman", "Delhi"),    new(2, "Priya", "Mumbai"),    new(3, "Neha", "Pune")]; Order[] orders = [    new(101, 1, "Mixer", 2499),    new(102, 2, "Bottle", 399),    new(103, 1, "Kettle", 1299),    new(104, 2, "Cooker", 1899)]; record Customer(int Id, string Name,    string City);record Order(int Id, int CustomerId,    string Item, decimal Amount);

31.3 Join is an inner join

  • Join takes the outer key (c.Id), the inner key (o.CustomerId) and a result selector that combines a matching pair.
  • It returns only pairs whose keys match on both sides, exactly like SQL INNER JOIN.
  • A customer with no matching order is dropped silently: no exception, no warning.
C#
var report = customers.Join(orders,    c => c.Id,    o => o.CustomerId,    (c, o) =>        $"{c.Name}: {o.Item} {o.Amount}"); foreach (var line in report)    Console.WriteLine(line);
Output
$ dotnet run Join.csAman: Mixer 2499Aman: Kettle 1299Priya: Bottle 399Priya: Cooker 1899
Where did Neha go?
  1. 1.Join compares c.Id with o.CustomerId

  2. 2.Aman (1), Priya (2): keys match, pairs made

  3. 3.Neha (Id 3): no order with CustomerId 3

  4. 4.Inner join drops Neha, no error

Need every customer? Use LeftJoin

31.4 LeftJoin (.NET 10)

  • Write LeftJoin instead of Join: every item on the left side (every customer) appears in the result.
  • When there is no match the right side (o) is null, so the result selector must check o is null.
  • .NET 10 also adds RightJoin, which keeps every item on the right side.
  • In older code the same left join is GroupJoin + SelectMany + DefaultIfEmpty.
C#
var report = customers.LeftJoin(orders,    c => c.Id,    o => o.CustomerId,    (c, o) => o is null        ? $"{c.Name}: no orders"        : $"{c.Name}: {o.Item} {o.Amount}"); foreach (var line in report)    Console.WriteLine(line);
Output
$ dotnet run LeftJoin.csAman: Mixer 2499Aman: Kettle 1299Priya: Bottle 399Priya: Cooker 1899Neha: no orders
C#
// Before .NET 10: GroupJoin + SelectMany + DefaultIfEmptyvar report = customers    .GroupJoin(orders, c => c.Id, o => o.CustomerId,        (c, os) => new { c, os })    .SelectMany(x => x.os.DefaultIfEmpty(),        (x, o) => o is null            ? $"{x.c.Name}: no orders"            : $"{x.c.Name}: {o.Item} {o.Amount}");

31.5 GroupBy: totals per customer

  • GroupBy(o => o.CustomerId) puts every order into the group for its CustomerId; g.Key is that CustomerId.
  • Inside Select, run aggregates per group: g.Count() and g.Sum(o => o.Amount).
  • GroupBy creates groups only for keys that exist in the data, so Neha gets no group here either.
  • To report every customer including zeros, start from customers and LeftJoin/GroupJoin the orders.
C#
var summary = orders    .GroupBy(o => o.CustomerId)    .Select(g => new    {        Id = g.Key,        Count = g.Count(),        Total = g.Sum(o => o.Amount)    }); foreach (var s in summary)    Console.WriteLine($"{s.Id}: " +        $"{s.Count} orders, {s.Total}");
Output
$ dotnet run GroupBy.cs1: 2 orders, 37982: 2 orders, 2298
The GroupBy flow
  1. 1.Take the key from every item: o.CustomerId

  2. 2.Items with the same key go into one group

  3. 3.Group 1: Mixer, Kettle; group 2: Bottle, Cooker

  4. 4.Aggregate per group: Count, Sum

  5. 5.Project with Select into { Id, Count, Total }

No group for Neha: she has no orders

31.6 Aggregates: Sum, Average, Max, MaxBy, CountBy

  • Aggregates turn a whole sequence into one value: Sum, Average, Min, Max, Count.
  • MaxBy / MinBy (.NET 6) return the whole element with the highest/lowest key, not just the number.
  • CountBy (.NET 9) does GroupBy + Count in one step and yields (key, count) pairs.
  • Aggregates run immediately: they enumerate the query right away.
C#
var amounts = orders.Select(o => o.Amount);Console.WriteLine(amounts.Sum());Console.WriteLine(amounts.Average());Console.WriteLine(amounts.Max()); var top = orders.MaxBy(o => o.Amount);Console.WriteLine(top?.Item); foreach (var (id, n) in    orders.CountBy(o => o.CustomerId))    Console.WriteLine($"{id}: {n}");
Output
$ dotnet run Aggregates.cs609615242499Mixer1: 22: 2

31.7 SelectMany: flatten a list of lists

  • Select returns one item per source item, so selecting an array per cart gives a list of arrays (count 2).
  • SelectMany flattens all the inner arrays into one sequence (count 4).
  • Distinct then removes the duplicate Kettle, which is in both carts.
C#
Cart[] carts = [    new("Aman", ["Mixer", "Kettle"]),    new("Priya", ["Bottle", "Kettle"])]; var nested = carts.Select(c => c.Items);var flat = carts.SelectMany(c => c.Items); Console.WriteLine(nested.Count());Console.WriteLine(flat.Count());Console.WriteLine(    string.Join(", ", flat.Distinct())); record Cart(string User, string[] Items);
Output
$ dotnet run SelectMany.cs24Mixer, Kettle, Bottle

31.8 Chunk: fixed-size batches

  • Chunk(n) splits a sequence into arrays of size n.
  • The last chunk keeps the remainder: Chunk never drops items.
  • Checkpoint: 10 ids with Chunk(4) give 3 batches (4 + 4 + 2).
C#
int[] orderIds = [101, 102, 103, 104, 105,    106, 107, 108, 109, 110]; foreach (var batch in orderIds.Chunk(4))    Console.WriteLine(        $"Batch: {string.Join(", ", batch)}");
Output
$ dotnet run Chunk.csBatch: 101, 102, 103, 104Batch: 105, 106, 107, 108Batch: 109, 110

31.9 Comparison: the operators

OperatorWhat it doesResult for the shop data
JoinInner join: only matching pairs4 lines, Neha missing
LeftJoin (.NET 10)Every left item, null if no match5 lines, Neha: no orders
GroupBy + Count/SumGroups by key, aggregate per group1: 2 orders, 3798 / 2: 2 orders, 2298
CountBy (.NET 9)GroupBy + Count in one step1: 2 / 2: 2
MaxByElement with the highest keyMixer
SelectManyFlattens nested lists4 items, 3 distinct
Chunk(4)Fixed-size batches3 batches

31.10 Common mistakes

  • Using Join when every left item must appear: unmatched rows vanish silently. Use LeftJoin.
  • Calling Max, Min or Average on a sequence that may be empty: InvalidOperationException "Sequence contains no elements".
  • Sum returns 0 on an empty sequence; for Max add DefaultIfEmpty(0) first.
  • Myth: "LINQ is always slow, use for loops in production". LINQ is optimized in every .NET release; if a hot path is in doubt, measure with BenchmarkDotNet.
C#
var nehaOrders = orders    .Where(o => o.CustomerId == 3)    .Select(o => o.Amount); Console.WriteLine(nehaOrders.Max());// InvalidOperationException:// Sequence contains no elements
C#
var nehaOrders = orders    .Where(o => o.CustomerId == 3)    .Select(o => o.Amount); Console.WriteLine(nehaOrders.Sum());Console.WriteLine(    nehaOrders.DefaultIfEmpty(0).Max());// 0// 0

31.11 Rules

  1. Join = inner; need all left items: LeftJoin (.NET 10).
  2. After GroupBy use Count/Sum inside Select; only counts needed: CountBy.
  3. Nested lists: SelectMany.
  4. Possibly empty Max/Average: DefaultIfEmpty first.
  5. Sending large data in batches: Chunk.

31.12 Interview tips

  • Join vs LeftJoin: Join returns only matching pairs; LeftJoin keeps every left item and gives null for a missing right side.
  • On .NET 10 use LeftJoin directly; earlier versions use GroupJoin + SelectMany + DefaultIfEmpty.
  • Grouping: GroupBy then aggregates in Select, or CountBy when you only need counts.
  • Max/Min/Average throw on an empty sequence, Sum returns 0.
  • SelectMany flattens; Chunk batches and keeps the remainder.