O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Lazy Evaluation

Their piecemeal on-demand evaluation characteristic makes iterators an ideal construct to express queries. Because the underlying data source can potentially change after you have declared a query expression, delaying the execution is a much desirable feature:

var nums = new List<int> { 2, 5, 7, 4, 1, 9 };var evens = from n in nums            where n % 2 == 0            select n;// Shows 2, 4foreach (var n in evens)    Console.WriteLine(n);// Somehow the collection changes, e.g. because the user edits the data.nums.Add(5);nums.Add(8);// Shows 2, 4, 8 - no need to redeclare the queryforeach (var n in evens)    Console.WriteLine(n);

The query expression used here is compiled into a call to the Where ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required