LINQ Interview Question #83

How can you avoid unnecessary multiple enumeration?

Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate

Quick Interview Answer

Materialize a sequence once when its results will be reused and a snapshot is appropriate. A List<T> or array can then be enumerated repeatedly without re-running the original deferred pipeline.

Detailed Explanation

Materialize a sequence once when its results will be reused and a snapshot is appropriate. A List<T> or array can then be enumerated repeatedly without re-running the original deferred pipeline.

Do not materialize automatically, however. Materialization consumes memory and can prevent later operations from being translated by a remote query provider.

Code Example

var activeItems = GetItems()
    .Where(x => x.IsActive)
    .ToList();

int count = activeItems.Count;

foreach (var item in activeItems)
    Console.WriteLine(item.Name);