Skip to content
Codescope

LINQ & deferred execution

Building a query runs nothing. The last operator pulls each element through, one at a time.

core10 min7 steps

Before you start

LINQ lets you write queries against collections that read like English: Where, Select, OrderBy. The catch is that these operations do not actually run when you write them.

Instead, they build up a *plan* — a pipeline waiting for someone to pull items through. Only when you call something like .ToList() or iterate with foreach does the pipeline actually execute, one element at a time.

This lesson makes the pipeline visible: watch elements flow through each stage exactly when they're needed, and see why enumerating the same query twice runs it twice.

LINQ pipeline

data is pulled from the end, not pushed from the start
numbers[]the only real collection
1
2
3
4
5
6
Where(n => n % 2 == 0)a filter, not a collection
in
—
passes?
—
Select(n => n * 10)a projection
yields
—
foreachpulls one at a time
nothing yet
?

var query is not a result. It is a recipe, and recipes do not cook themselves.

Step 1 of 7. Defining the query executes nothing. After both lines, `query` holds an object that *describes* the work — a `Where` wrapped around the array, and a `Select` wrapped around that. No element has been examined. No lambda has been called. Set a breakpoint inside the `Where` predicate and it will not be hit yet.

01 / 07

Step 01 / 07

Defining the query executes nothing

After both lines, query holds an object that *describes* the work — a Where wrapped around the array, and a Select wrapped around that.

No element has been examined. No lambda has been called. Set a breakpoint inside the Where predicate and it will not be hit yet.

Program.csC#
int[] numbers = { 1, 2, 3, 4, 5, 6 };var query = numbers    .Where(n => n % 2 == 0)     // nothing runs yet    .Select(n => n * 10);       // still nothingforeach (var n in query) { }    // now it runsvar list = query.ToList();      // runs again, from scratchvar first = numbers.Where(n => n > 3).First();  // stops early