What are the benefits of a Deferred Execution in LINQ?

Technology CommunityCategory: C#What are the benefits of a Deferred Execution in LINQ?
VietMX Staff asked 3 years ago

In LINQ, queries have two different behaviors of execution: immediate and deferred. Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.

Consider:

var results = collection.Select(item => item.Foo).Where(foo => foo < 3).ToList();

With deferred execution, the above iterates your collection one time, and each time an item is requested during the iteration, performs the map operation, filters, then uses the results to build the list.

If you were to make LINQ fully execute each time, each operation (Select / Where) would have to iterate through the entire sequence. This would make chained operations very inefficient.