skip to content

In a C# query expression, what do a second from and a let clause compile to, and how do earlier range variables stay in scope?

level: middleimportance: should knowfreq 30%

answer

  1. nested loops, flattened
  2. the second from is not a join
  3. let costs one more projection
  4. hidden anonymous objects
  5. transparent identifiers

basics

~20 s

A second from compiles to SelectMany, and let compiles to a Select that wraps the current range variables and the new value in an anonymous object. These hidden objects, called transparent identifiers, keep earlier range variables reachable in later clauses.

solid answer

~50 s

`from author in authors from book in author.Books` becomes `authors.SelectMany(author => author.Books, (author, book) => new { author, book })`: the result selector packs both range variables into an anonymous object so later clauses can still say `author` and `book`. `let daysLate = …` becomes `.Select(x => new { x, daysLate = … })`, one more anonymous object per element. Every later mention of `author` or `daysLate` is rewritten as a member access through these objects, which are known as *transparent identifiers*. When the second `from` is followed directly by `select`, the projection goes straight into `SelectMany`'s result selector and no wrapper is built. A `let` variable is read-only (CS1947). Writing the same query in method syntax means naming and nesting those objects yourself, which is why such queries usually read better in query syntax.

code

csharp · 31 lines
csharp
using System.Linq;

var today = new DateOnly(2026, 10, 10);
Author[] authors =
[
    new("Achebe", [new("Things Fall Apart", [new("ana", new(2026, 10, 1))])]),
    new("Morrison", [new("Beloved", [new("cy", new(2026, 9, 30)), new("di", new(2026, 10, 20))]), new("Sula", [])]),
];

var overdue =
    from author in authors
    from book in author.Books          // second from: SelectMany
    from loan in book.Loans            // third from: SelectMany again
    let daysLate = today.DayNumber - loan.Due.DayNumber   // let: Select into a new anonymous type
    where daysLate > 0
    select $"{author.Name} / {book.Title}: {loan.Member}, {daysLate} days late";

// Roughly what the compiler writes; the anonymous types carry every range variable forward.
var lowered = authors
    .SelectMany(author => author.Books, (author, book) => new { author, book })
    .SelectMany(ab => ab.book.Loans, (ab, loan) => new { ab, loan })
    .Select(x => new { x, daysLate = today.DayNumber - x.loan.Due.DayNumber })
    .Where(y => y.daysLate > 0)
    .Select(y => $"{y.x.ab.author.Name} / {y.x.ab.book.Title}: {y.x.loan.Member}, {y.daysLate} days late");

foreach (var line in overdue) Console.WriteLine(line);
Console.WriteLine(overdue.SequenceEqual(lowered));   // True

record Author(string Name, List<Book> Books);
record Book(string Title, List<Loan> Loans);
record Loan(string Member, DateOnly Due);

go deeper

for a junior

Recall that two from clauses flatten nested collections like nested foreach loops, and that let names a value computed once per element.

for a middle

Explain the translation: SelectMany with a collection selector and a result selector, let as a Select into an anonymous object, and how transparent identifiers keep earlier names in scope.

for a senior

Spot the costs in review: an allocation per element per let, a collection selector that runs once per outer element, and a cross product filtered by where where a join would scale better.

for a principal

When a team debates query versus method syntax, point at queries with several from or let clauses: hand-written transparent identifiers are the maintenance cost query syntax removes.

## A second from is SelectMany A query expression starts with `from x in source`, which declares the **range variable** `x`. A second `from` clause declares another range variable over a collection that may depend on the first, like a nested `foreach`: ```csharp from author in authors from book in author.Books select $"{author.Name}: {book.Title}" ``` The compiler translates this into one call to `Enumerable.SelectMany` with two lambdas: a **collection selector** (`author => author.Books`) that produces the inner sequence for each author, and a **result selector** (`(author, book) => $"…"`) that receives both range variables. The result is flat: one string per author-and-book pair, not one nested list per author. If the inner `from` ranges over an unrelated source (`from b in books`), the same translation gives a cross product, and a following `where b.AuthorId == a.Id` filters it into a join that can test any condition, not only equality; the dedicated `join` clause, covered separately, builds a key lookup instead of testing every pair. ## let is a Select into an anonymous object `let daysLate = today.DayNumber - loan.Due.DayNumber` introduces a new range variable computed once per element. There is no `Let` operator; the compiler emits ```csharp .Select(x => new { x, daysLate = today.DayNumber - x.loan.Due.DayNumber }) ``` so each element is wrapped in a fresh **anonymous-type** object holding what was in scope plus the new value. Later clauses read `daysLate` from that object instead of recomputing the expression, which is the point of `let`: an expensive or repeated subexpression (a `ToLower()`, a date difference, a parsed value) is evaluated once per element. ## Transparent identifiers, step by step When more clauses follow a second `from` or a `let`, the compiler must carry every earlier range variable forward. It does so with **transparent identifiers**: compiler-named parameters whose anonymous-type members stand for the original names. For the overdue-loan query in the example, the chain is: 1. `SelectMany(author => author.Books, (author, book) => new { author, book })` 2. `SelectMany(ab => ab.book.Loans, (ab, loan) => new { ab, loan })` 3. `Select(x => new { x, daysLate = … })` for the `let` 4. `Where(y => y.daysLate > 0)` 5. `Select(y => … y.x.ab.author.Name …)` for the final `select` In query syntax you still write `author.Name`; the compiler rewrites it as a path through the nested objects. The final `select` is fused into the last call where it can be: a second `from` followed directly by `select` puts the projection into `SelectMany`'s result selector, with no wrapper object. ## Rules and costs - A range variable introduced by `let` or `from` is read-only. `where (y = 3) > 0` fails with CS1947: "Range variable 'y' cannot be assigned to -- it is read only". - Each `let` adds one `Select` call and one small heap object per element that reaches it. In a hot loop over millions of elements that allocation is measurable; elsewhere it is noise. - The collection selector of a second `from` runs once per outer element, so an expensive expression there runs many times. - A cross product filtered by `where` evaluates the predicate for every pair; for an equality match, `join` scales better. | Construct | Translation | Extra objects per element | |---|---|---| | `from a in xs from b in a.Ys select …` | `SelectMany` with a result selector | none | | `from a … from b … where …` | `SelectMany` into `new { a, b }`, then `Where` | one per pair | | `let v = expr` | `Select(x => new { x, v = expr })` | one | ## Choosing the spelling The method-syntax version of a three-level query with a `let` must spell out `new { author, book }`, `new { ab, loan }` and `y.x.ab.author.Name` by hand. That bookkeeping is exactly what query syntax hides, and it is the strongest reason to choose query syntax: queries that flatten nested collections, or that name an intermediate value, read top to bottom like the nested loops they describe. A chain with a single `SelectMany` and no later clauses reads just as well as a method call.

  • Why does let in a C# query expression avoid recomputing an expression, and what does that cost?
    `let` becomes a `Select` that stores the computed value in a new anonymous object next to the current range variables, so later `where`, `orderby` and `select` clauses read the stored member instead of re-evaluating the expression. The cost is one extra `Select` stage and one small heap object for every element that reaches it.
  • How does from a in authors from b in books where b.AuthorId == a.Id differ from a join clause on the same keys?
    Both return the same pairs, but the double `from` is a `SelectMany` cross product followed by `Where`, so the predicate runs for every author-book pair. `join … on a.Id equals b.AuthorId` translates to `Join`, which builds a lookup of the inner keys once and matches each outer key against it. The double `from` form is the one to use when the condition is not equality.

  • A second from clause in a C# query compiles to Join.
  • let re-evaluates its expression each time a later clause reads it.
  • A let variable can be reassigned in a later where clause.
  • Two from clauses produce one nested list per outer element.
  • Transparent identifiers are a run-time lookup by variable name.