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