A query expression declaratively describes sequence or collection transformations, allowing the compiler and runtime to translate meaning-focused syntax into executable operations. It replaces mechanism-heavy nested loops with an expression that states which combinations to select. section 6.1
Reporting character–weapon compatibility
Given character and weapon sets, nested loops enumerate every pair. A C# query expression uses two from clauses and a select clause to produce the same report: each character is paired with each weapon, then CanWield determines the result. This is the Cartesian product of the two sets, also recognizable as a SQL CROSS JOIN. section 6.1
var q = from c in cs
from w in ws
select $"{c.Name} {w.Name} {c.CanWield(w)}";
var s = string.Join("\n", q);
The two from clauses expose the product structure directly: choose an item from the first sequence, then an item from the second, and select the resulting value. section 6.1
Query expressions become especially useful when the transformation scales beyond two sequences:
- Build an arbitrary Cartesian product by successively appending one element from each input sequence to existing partial sequences. section 6.1.2
- Preserve immutability with PushRight on an immutable deque rather than copying or mutating existing sequences. section 6.1.2
- Defer execution: constructing the nested query takes O(n) for n input sequences, while iteration bears the execution cost. section 6.1.2
- Replace the visible accumulation loop with .NET's Aggregate extension method when that style improves the presentation. section 6.1.2
