1 using System;
2 using System.Linq;
3
4 namespace Linq101
5 {
6 class QueryExecution
7 {
8 /// <summary>
9 /// The following sample shows how query execution is deferred until the query is enumerated at a foreach statement.
10 /// </summary>
11 public void Linq99()
12 {
13 int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
14
15 int i = 0;
16
17 //延迟执行
18 var q = from n in numbers select ++i;
19
20 foreach (int n in q)
21 {
22 Console.WriteLine("n={0},i={1}", n, i);
23 }
24 }
25
26 /// <summary>
27 /// The following sample shows how queries can be executed immediately with operators such as ToList().
28 /// </summary>
29 public void Linq100()
30 {
31 int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
32
33 int i = 0;
34
35 //ToList->立即执行
36 var q = (from n in numbers select ++i).ToList();
37
38 foreach (int n in q)
39 {
40 Console.WriteLine("n={0},i={1}", n, i);
41 }
42 }
43
44 /// <summary>
45 /// 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.
46 /// </summary>
47 public void Linq101()
48 {
49 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
50
51 //可重用
52 var lowNumbers = from n in numbers
53 where n <= 3
54 select n;
55
56 Console.WriteLine("First run numbers <=3:");
57 foreach (int number in lowNumbers)
58 {
59 Console.WriteLine(number);
60 }
61
62 lowNumbers = (from n in numbers select -n).ToArray();
63
64 Console.WriteLine("Second run numbers <=3:");
65 foreach (int number in lowNumbers)
66 {
67 Console.WriteLine(number);
68 }
69 }
70 }
71 }