Sunday, October 31, 2010

yield keyword : Lazy and Eager Evaluation

The most important element of the Where extension method code is the yield return item
instruction that the iterator executes if item meets the Where criterion ( predicate expression). C# 2.0
introduced the yield contextual keyword but few developers used it. The compiler recognizes yield as
a keyword only if it ’ s followed by return or break . The yield return item instruction in an iterator
block enables an enumerable class to be implemented in terms of another enumerable class; that is,
chained.

Lazy and Eager Evaluation
The yield return item instruction enables lazy evaluation , which is another feature critical to LINQ.
Lazy evaluation means that a LINQ code doesn ’ t touch the query ’ s data source until the code executes
the iterator ’ s first yield return item instruction. Lazy evaluation makes execution of chained
extension methods very efficient by eliminating storage of intermediate results. Lazy evaluation is the
key to object/relational mapping (O/RM) tools ’ lazy loading of objects related to your main object by
associations. Lazy loading means that the O/RM tool doesn ’ t load related objects until the application
needs to access their property values.
Eager evaluation means that the query is self - executing. For example, chaining an aggregate function to
the end of a query causes immediate evaluation. The following snippets demonstrate eager evaluation
with the Count() expression method in query expression and method call syntax:
C# 3.0
var noStockCount1 = (from p in productList
where p.UnitsInStock == 0
select p).Count();
result = “\r\nCount of out-of-stock items = “ + noStockCount1.ToString();
var noStockCount2 = productList
.Where(p = > p.UnitsInStock == 0)
.Count();
result = “\r\nCount of out-of-stock items = “ + noStockCount2.ToString();

No comments:

Post a Comment