Complex grouping and query cost
Complex grouping and query cost
Advanced LINQ involves shaping results while controlling how much data is read, buffered and processed. Grouping and sorting may need substantial state; pagination limits the result only when its placement and ordering are appropriate. Measure the actual provider, data volume and workload rather than assuming that a short query is cheap.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Group by a composite key
Use a tuple key in LINQ to Objects to group by more than one field. Grouping collects elements by equality; a later projection can summarize each group. A remote provider may require a different expression shape, such as an anonymous type, and support for grouped projections varies.
using System;using System.Linq;var rows = new[] { (Day: 1, Zone: "B", Qty: 2), (Day: 1, Zone: "A", Qty: 4), (Day: 1, Zone: "A", Qty: 3), (Day: 2, Zone: "A", Qty: 1) };var summary = rows.GroupBy(r => (r.Day, r.Zone)) .Select(g => (g.Key.Day, g.Key.Zone, Total: g.Sum(r => r.Qty))) .OrderBy(x => x.Day).ThenBy(x => x.Zone, StringComparer.Ordinal);foreach (var row in summary) Console.WriteLine($"{row.Day}:{row.Zone}:{row.Total}");Repeated lines contribute to the same total; grouping is not deduplication. Explicit ordering makes the display predictable.
Expected output (reasoned, not executed):
1:A:71:B:22:A:1Page by a stable ordering
Offset pagination uses Skip and Take after ordering. Choose a unique tie-breaker to avoid ambiguous page membership. Keyset pagination instead filters after the last ordered key and takes the next batch; it is good for sequential navigation when indexes and query shape support it. Concurrent changes can still affect results.
using System;using System.Linq;int[] ids = { 40, 10, 30, 20, 50 };var ordered = ids.OrderBy(id => id);Console.WriteLine(string.Join(",", ordered.Skip(2).Take(2)));int lastSeen = 20;Console.WriteLine(string.Join(",", ordered.Where(id => id > lastSeen).Take(2)));Console.WriteLine(string.Join(",", ordered.Where(id => id > 50).Take(2).DefaultIfEmpty(-1)));Both return the same second page in this fixed fixture. The last line uses a display sentinel for an empty page, not an actual record.
Expected output (reasoned, not executed):
30,4030,40-1Batch, deduplicate and parallelize deliberately
Chunk groups a sequence into arrays of at most the requested size (positive size required). DistinctBy deduplicates on selected keys; do not rely on a particular representative or ordering where not contractually guaranteed. PLINQ may run operators concurrently; preserve ordering explicitly where required, avoid shared mutation and benchmark overhead.
using System;using System.Linq;int[] values = { 4, 2, 4, 1, 2 };foreach (var batch in values.Chunk(2)) Console.WriteLine(string.Join(",", batch));Console.WriteLine(values.DistinctBy(n => n).Count());Console.WriteLine(string.Join(",", values.AsParallel().AsOrdered().Select(n => n * 2)));The last chunk is short, distinct keys number three, and AsOrdered preserves the source ordering of the parallel projection. This does not demonstrate a speedup.
Expected output (reasoned, not executed):
4,24,1238,4,8,2,4Common mistakes and edge cases
Do not paginate without a deterministic ordering, or sort only on a nonunique column. Sorting and grouping can require consuming the entire finite source; Take after OrderBy does not make an unbounded sort safe. Chunk can stream bounded batches but materializing all chunks still grows memory. PLINQ is not a database query optimizer; do not put side effects in parallel selectors. The .NET 10 Enumerable and Queryable APIs include LeftJoin and RightJoin. Their in-memory semantics are documented, but translation and performance remain provider-specific; inspect and test the actual provider. Earlier GroupJoin and DefaultIfEmpty patterns remain valid.
Practice and recap
Given unsorted IDs [9,3,5,1,7], page in batches of two. Write a keyset filter after ID 3 and compare offset page 2. Then split the sorted results with Chunk(2).
Hint: Sort first and use a strict greater-than predicate for the cursor.
Learning objective: Choose materialization and ordering consciously. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Complex grouping and query cost — knowledge check
Apply the lesson concepts to the following scenarios.
Which grouping key combines day and zone in LINQ to Objects?
What makes pagination ordering deterministic on a fixed dataset?
What does keyset pagination use to find the next page?
How many elements are in the final Chunk(2) for five values?
Why use AsOrdered in PLINQ?