Friday, September 10, 2010

Deferred Execution of LINQ Query Expressions


An important feature of LINQ query expressions is deferred execution. What this means is that LINQ query expressions are not evaluated until you iterate over the (would be) resultset. This has a very important implication -- this enables you to apply the same LINQ query multiple times to a container by simply iterating over it and be sure that each time you do, you get the latest results.

The following example demonstrates this feature:

static void Main(string[] args) {
   // Define a set of numbers; query to select even numbers.
   int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   var results = from i in numbers
                 where i % 2 == 0
                 select i;

   // Display results; the LINQ query is evaluated here!
   Console.WriteLine("Even numbers (original)...");
   foreach (var i in results) {
       Console.WriteLine(i);
   }

   // Modify the array to include two more even numbers.
   numbers[6] = 12;
   numbers[8] = 14;

   // Display results; the LINQ query is AGAIN evaluated here!
   Console.WriteLine("\nEven numbers (modified)...");
   foreach (var i in results) {
       Console.WriteLine(i);
   }

   Console.ReadLine();

}

Here's the output you get:

Even numbers (original)...
2
4
6
8
10

Even numbers (modified)...
2
4
6
12
8
14
10

Happy coding!

0 comments: