On Sep 16, 11:22 am, raylopez99 <raylope...@yahoo.comwrote:
I'm reading a book that talks about how some operations, like LINQ
queries, are "deferred execution" while other queries are "immediate
execution".
What is the difference?
RL
Consider this code:
static void Main(string[] args) {
//An array of integers
int[] numbers = { 1, 2, 3, 4};
//query the array for all even numbers
var query = from n in numbers
select Square(n);
//iterate through the results
foreach (int i in query) {
Console.WriteLine(i.ToString());
}
Console.ReadLine();
}
public static double Square(double n) {
Console.WriteLine("Computing Square(" + n + ")...");
return Math.Pow(n, 2);
}
When you run it, you see this output:
Computing Square(1)...
1
Computing Square(2)...
4
Computing Square(3)...
9
Computing Square(4)...
16
Notice that the line that says "Computing Square" for each number is
not executed until the foreach is executed. In other words the Square
method is not called until you iterate the query. But if you change
the foreach to look like this (note the addition of ToList():
//iterate through the results
foreach (int i in query.ToList()) {
Console.WriteLine(i.ToString());
}
The result is this:
Computing Square(1)...
Computing Square(2)...
Computing Square(3)...
Computing Square(4)...
1
4
9
16
All the squares are calculated before they are displayed. The first
example is deferred execution of the query. The second example
(ToList) is immediate execution.
Hope this helps a little.
Chris