Tagged: LINQ

Yield, Lazy and Eager Evaluation and Deferred Execution

Yield return provides a way to iterate through collections. From a performance perspective this allows you to defer execution until it is needed (or even to avoid loading the entire collection if not all the elements are required).

This concept is essential for LINQ as a query language. These resulting queries don’t execute until they are actually required; also known as lazy evaluation. To force an eager load or an iteration across the entire list you can simply call ToList().

Deferred execution just refers to the delayed execution of the initial set of operations required to iterate over a list. For example the OrderBy operator requires the entire list to be sorted before it can yield the initial result. So the deferred execution can be lazy or eager evaluated.

<Eric White’s Article>