101 LINQ Samples: Query Execution

Deferred Execution

The following sample shows how query execution is deferred until the query is enumerated at a foreach statement.


     
       
  1. public void Linq99()
  2. {
  3.     // Sequence operators form first-class queries that
  4.     // are not executed until you enumerate over them.
  5.  
  6.     int[] numbers = new int[] { 5413986720 };
  7.  
  8.     int i = 0;
  9.     var q =
  10.         from n in numbers
  11.         select ++i;
  12.  
  13.     // Note, the local variable 'i' is not incremented
  14.     // until each element is evaluated (as a side-effect):
  15.     foreach (var v in q)
  16.     {
  17.         Console.WriteLine("v = {0}, i = {1}", v, i);
  18.     }
  19. }

Result

v = 1, i = 1
v = 2, i = 2
v = 3, i = 3
v = 4, i = 4
v = 5, i = 5
v = 6, i = 6
v = 7, i = 7
v = 8, i = 8
v = 9, i = 9
v = 10, i = 10

Immediate Execution

The following sample shows how queries can be executed immediately with operators such as ToList().


     
       
  1. public void Linq100()
  2. {
  3.     // Methods like ToList() cause the query to be
  4.     // executed immediately, caching the results.
  5.  
  6.     int[] numbers = new int[] { 5413986720 };
  7.  
  8.     int i = 0;
  9.     var q = (
  10.         from n in numbers
  11.         select ++i)
  12.         .ToList();
  13.  
  14.     // The local variable i has already been fully
  15.     // incremented before we iterate the results:
  16.     foreach (var v in q)
  17.     {
  18.         Console.WriteLine("v = {0}, i = {1}", v, i);
  19.     }
  20. }

Result

v = 1, i = 10
v = 2, i = 10
v = 3, i = 10
v = 4, i = 10
v = 5, i = 10
v = 6, i = 10
v = 7, i = 10
v = 8, i = 10
v = 9, i = 10
v = 10, i = 10

Query Reuse

The following sample shows how, because of deferred execution, queries can be used again after data changes and will then operate on the new data.


     
       
  1. public void Linq101()
  2. {
  3.     // Deferred execution lets us define a query once
  4.     // and then reuse it later after data changes.
  5.  
  6.     int[] numbers = new int[] { 5413986720 };
  7.     var lowNumbers =
  8.         from n in numbers
  9.         where n <= 3
  10.         select n;
  11.  
  12.     Console.WriteLine("First run numbers <= 3:");
  13.     foreach (int n in lowNumbers)
  14.     {
  15.         Console.WriteLine(n);
  16.     }
  17.  
  18.     for (int i = 0; i < 10; i++)
  19.     {
  20.         numbers[i] = -numbers[i];
  21.     }
  22.  
  23.     // During this second run, the same query object,
  24.     // lowNumbers, will be iterating over the new state
  25.     // of numbers[], producing different results:
  26.     Console.WriteLine("Second run numbers <= 3:");
  27.     foreach (int n in lowNumbers)
  28.     {
  29.         Console.WriteLine(n);
  30.     }
  31. }

Result

First run numbers <= 3:
1
3
2
0
Second run numbers <= 3:
-5
-4
-1
-3
-9
-8
-6
-7
-2
0

你可能感兴趣的:(sample)