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 ...
Get C# 5.0 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.