LINQ Interview Question #82
What is multiple enumeration in LINQ?
Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate
Quick Interview Answer
Multiple enumeration occurs when an IEnumerable<T> query is enumerated more than once. With a deferred query, the underlying operations can run again each time.
Detailed Explanation
Multiple enumeration occurs when an IEnumerable<T> query is enumerated more than once. With a deferred query, the underlying operations can run again each time.
This can be inexpensive for small in-memory collections, but it can be costly or undesirable for database queries, file streams, network-backed sequences, or expensive calculations.
Code Example
var query = GetItems().Where(x => x.IsActive);
int count = query.Count(); // Enumeration
foreach (var item in query) // Another enumeration
{
Console.WriteLine(item.Name);
}