SP
← LINQ
SeniorLINQ

LINQ internals: pipelines, providers and cost

The pipeline is a chain of enumerators

Each deferred operator wraps its source in an iterator object. Enumerating the outermost one pulls elements through the chain one at a time: foreach calls MoveNext on Where, which calls MoveNext on Select, which reads the array. Streaming operators (Where, Select, Take, Skip, SelectMany, Concat) therefore interleave their work per element:

var q = src.Select(x => Log("S", x)).Where(x => Log("W", x) != 2);
// order of calls: S1 W1 [1] S2 W2 S3 W3 [3]

Non-streaming operators (OrderBy, ThenBy, GroupBy, Reverse, and the inner side of Join) are still deferred, but on the first MoveNext they must read the entire source into a buffer, because the first result could depend on the last element. Consequences: Select(...).OrderBy(...) runs every selector before the first result even if you break immediately, buffering operators never finish on infinite sequences, and they hold the whole input in memory.

Iterators and argument validation

A method containing yield return is compiled into a state machine. Calling it only creates the object; the body, including any argument checks at the top, runs on the first MoveNext. For a custom operator that means a null argument is reported far from the faulty call. Split the operator in two, as the built-in operators do:

public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> source)
{
    ArgumentNullException.ThrowIfNull(source); // runs at call time
    return Iterate(source);

    static IEnumerable<T> Iterate(IEnumerable<T> s)
    {
        int i = 0;
        foreach (var item in s)
            if (i++ % 2 == 0) yield return item;
    }
}

Disposal and finally blocks in iterators

yield return suspends the iterator inside its try block; it does not leave it. Pending finally blocks (and using disposals) run when the enumerator is disposed. foreach always disposes, including after break, and so do operators such as First and Take once they stop pulling. So Numbers().First() runs the iterator's finally right after taking the first element, not at the end of the sequence and not on garbage collection. If you call GetEnumerator() by hand, dispose it yourself, or the cleanup never runs.

Cost compared with loops

A LINQ pipeline allocates an iterator per operator, plus a closure object and delegate when the lambda captures locals. Each element passes through interface calls (MoveNext, Current) and delegate invocations that the JIT usually cannot inline. A foreach over List<T> uses a struct enumerator and allocates nothing. The runtime narrows the gap with special cases (array and list iterators, fused Where().Select()), but on a measured hot path a hand-written loop still wins. Everywhere else, prefer the clearer code. LINQ does not use reflection or copy the source.

Count, Length and TryGetNonEnumeratedCount

Count() checks whether the source is an ICollection<T> (or an internal iterator that knows its size) and returns the stored count in O(1). Otherwise it enumerates everything, on every call, since LINQ never caches results. TryGetNonEnumeratedCount exposes that check: true for a List<T>, false for a Where result. Prefer the Count/Length property when you have the concrete collection, and Any() for emptiness checks on lazy sequences.

Expression trees and providers

Queryable operators accept Expression<Func<...>>. The compiler builds a data structure describing the lambda, and the provider (EF Core) translates it to SQL. The provider sees only nodes: a call to your own IsVip(u) is just a MethodCallExpression, and the method body is compiled IL it cannot read. Since EF Core 3.0, an untranslatable expression outside the final projection throws InvalidOperationException ("could not be translated") instead of silently loading everything. Fixes: write the condition inline, return an Expression<Func<T, bool>> from a helper, or move to memory deliberately.

Drawing the boundary with AsEnumerable

AsEnumerable() executes nothing; it changes the static type so that the following operators bind to Enumerable. Everything before it becomes SQL, and everything after it runs in memory on rows that are streamed while the query is enumerated:

db.Orders.Where(o => o.Year == 2025)   // SQL WHERE
  .AsEnumerable()
  .Where(o => RiskScore(o) > 5)        // C#, per row
  .ToList();                           // query sent here

Filter and project as much as possible before the boundary.

PLINQ and thread safety

AsParallel() partitions the source and runs your delegates on several threads. Trade-offs:

  • Results come back in any order unless you add AsOrdered(), which costs extra.
  • Partitioning and merging have overhead; for cheap work or small inputs PLINQ is often slower than sequential LINQ. Measure.
  • PLINQ does not synchronize your lambdas. Adding to a shared List<T> from inside the query can lose items or corrupt the list. Return results through the query (Select(...).ToList()) or use a concurrent collection, and keep delegates free of shared mutable state.
  • A PLINQ query is deferred like any other; work starts when it is enumerated or forced with ToList/ForAll.
Practise this level
10 questions
Practise →