Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Assigning a LINQ sequence query usually does not retrieve its results. It describes the work to perform later. A foreach triggers that work by enumerating the sequence; scalar operators such as Count() and materializers such as ToList() execute before they return. Which work runs—and where—also depends on whether the source is an in-memory IEnumerable<T> or a provider-backed IQueryable<T>.

Why assigning a LINQ query does not run it

For a deferred sequence query, the variable holds the operations needed to produce values, not the values themselves. As Microsoft puts it, “In other words, you don’t retrieve any data by creating a query variable.” Microsoft Learn: Introduction to LINQ Queries (C#)

For example, creating this query describes a filter. The loop is what asks for its elements:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var query = numbers.Where(n => n % 2 == 0); // Describes the filter; results need not be read yet.

foreach (var n in query)                    // Enumeration runs the query.
    Console.WriteLine(n);

What forces a LINQ query to execute?

Enumerating a sequence

A foreach consumes the sequence and retrieves its elements. Other operations that enumerate it can do the same. A deferred query can run again each time it is enumerated; if its source changes, a later run may produce different values. Microsoft Learn: Introduction to LINQ Queries (C#)

Calling an operator that returns one value

Scalar operators such as Count(), Max(), Average(), and First() must inspect the sequence to return their result, so they execute immediately rather than returning a deferred sequence. Microsoft Learn: Introduction to LINQ Queries (C#)

Materializing with ToList() or ToArray()

These methods enumerate the source immediately and store the resulting elements in a collection. For instance:

var snapshot = query.ToList(); // Runs the query now and stores its results.

The collection can be reused without re-running that deferred query. It represents the results captured when it was created, not a live view that re-evaluates as the source changes. Materialization also retains the selected results in memory; the suitable cost depends on the workload. Microsoft Learn: Introduction to LINQ Queries (C#) Microsoft Learn: Enumerable.ToList Method

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

As a rule of thumb, use enumeration to consume a sequence, and materialize when you specifically need execution at that point and a reusable collection. Conversion methods beginning with To enumerate; As methods change the static type without enumerating. Microsoft Learn: Introduction to LINQ Queries (C#)

Deferred execution does not always mean streaming

Deferred execution means the work waits until enumeration. It does not promise that the query can produce its first result as soon as it reads the first input. Streaming operators such as Where and Select can produce results as input arrives. A nonstreaming operator such as OrderBy must process and sort the full source before it can return the first ordered result. The query is still deferred: the sorting begins when enumeration begins. Microsoft Learn: Introduction to LINQ Queries (C#) Microsoft Learn: Deferred Execution and Lazy Evaluation in LINQ to XML

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Does the source type change what runs?

IEnumerable<T>: sequence operations run during enumeration

For LINQ to Objects, operators commonly work over IEnumerable<T>. Their logic runs as the returned sequence is enumerated.

IQueryable<T>: a provider may translate the query

An IQueryable<T> represents a query as an expression tree. Its provider may translate that tree into a native or remote query; Entity Framework translating LINQ into SQL is one example. Providers differ in supported translations and restrictions, so a query that is valid in one context may not be supported by another. Enumeration or materialization is when the provider is asked to produce results, which can make provider or translation problems appear at that point. Consult the documentation for the provider in use. Microsoft Learn: Standard Query Operators Overview (C#) Microsoft Learn: Introduction to LINQ Queries (C#)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to diagnose a query that appears not to run

  1. Check what the variable represents. A variable typed as IEnumerable<T> or IQueryable<T> is a sequence query; a scalar-returning call such as Count() has already requested a value.
  2. Enumerate where you need the values. Use foreach to consume the sequence, or call ToList() or ToArray() if you need to run it now and retain the results.
  3. If a failure appears only at that point, inspect the source and provider. Deferred execution delays work until enumeration, and an IQueryable<T> provider may need to translate the expression then. Check the source enumerator or provider documentation.
  4. If you enumerate more than once, decide whether rerunning is intended. A deferred query can run again and observe changed source data. Materialize once if you need to reuse a captured result.
  5. Use side effects only as a temporary diagnostic. A breakpoint or observable side effect in a predicate or projection can help establish whether it is reached, but do not rely on side effects in query expressions as normal program behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.