Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. LINQ Pocket Reference > Deferred Execution

Deferred Execution

An important feature of most query operators is that they execute not when constructed, but when enumerated (in other words, when MoveNext is called on its enumerator). Consider the following query:

	var numbers = new List<int>( );
	numbers.Add (1);

	// Build query
	IEnumerable<int> query = numbers.Select (n => n * 10);
	numbers.Add (2);    // Sneak in an extra element

	foreach (int n in query)
	  Console.Write (n + "|");          // 10|20|

The extra number that we sneaked into the list after constructing the query is included in the result because it’s not until the foreach statement runs that any filtering or sorting takes place. This is called deferred or lazy evaluation. All standard query operators provide deferred execution, with the following exceptions:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial