liveBook · Manning

Query expression

As explained in Fabulous Adventures in Data Structures and Algorithms

A query expression is a declarative syntax for describing sequence or collection transformations that a compiler or runtime translates into executable operations.

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

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Explains syntax, Cartesian-product structure, arbitrary-sequence construction, deferred execution, and an Aggregate alternative without detailing compiler desugaring internals.
Examples
Demonstrates character–weapon compatibility, arbitrary products of numeric sequences, immutable deque construction, and concatenated product outputs.
What it assumes
Assumes familiarity with C# sequences and loops, while pointing unfamiliar readers toward a query-expression primer.
What you can do after
Build it from scratch by expressing two-way and arbitrary Cartesian products with C# query syntax and LINQ aggregation.
How it connects
Connects query expressions to nested loops, Cartesian products, CROSS JOIN, LINQ, immutable deques, lazy evaluation, and aggregation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.