Thursday, February 7, 2013

Deffered Execution



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

var numbers = new List<int>{1};
numbers.Add(1);
IEnumerable<int> query = numbers.Select(n=>n*10);
numbers.Add(2);

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


This is called differed or lazy evaluation.


The following conversion operators:
             ToArray, ToList, ToDictionary, ToLookup

The Conversion operators are useful, in part , because they defeat lazy evaluation. This can be useful when:

You want to "freeze" or cache the results at a certain point in time.

you want to avoid re-executing a computationally intensive query, or a query with a remote data source such as a LINQ  to SQL table. ( A side effect of lazy evaluation in that the query gets re-evaluated should you later re-enumerate it).

The following example illustrates the ToList operator:

var number = new List<int>(){1,2};

List<int> timesTen = numbers
.Select(n=>n*10)
.ToList(); //Executes immediately into a List<int>
number.Clear();
Console.WriteLine (timesTen.Count); // still 2


No comments:

Post a Comment

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code