准备数据:
- // 获取数据源
- int[] numbers = new int[]
- { 6, 4, 3, 2, 9, 1, 7, 8, 5 };
- // 定义查询
- var even = numbers
- .Select(p =>
- {
- Console.WriteLine("Hi! " + p.ToString());
- return p;
- })
- .Where(p => p % 2 == 0)
- .OrderBy(p => p);
在定义查询是查询没有执行,在控制台不输出任何东西,只有在用到查询结果或者调用其他一些返回单值的方法时才会执行:
foreach (var item in even) { Console.WriteLine(item); }
执行代码时会输出什么呢?结果:
Hi! 6
Hi! 4
Hi! 2
Hi! 8
Hi! 6
Hi! 4
Hi! 2
Hi! 8
2
4
6
8
如果查询定义修改为:
- var even = numbers
- .Where(p => p % 2 == 0)
- .Select(p =>
- {
- Console.WriteLine("Hi! " + p.ToString());
- return p;
- })
- .OrderBy(p => p);
结果为:
Hi! 6
Hi! 4
Hi! 2
Hi! 8
2
4
6
8
如果查询定义为:
- var even = numbers
- .Where(p =>
- {
- Console.WriteLine("W: " + p.ToString());
- return p % 2 == 0;
- })
- .Select(p =>
- {
- Console.WriteLine("S: " + p.ToString());
- return p;
- })
- .OrderBy(p => {
- Console.WriteLine("O: " + p.ToString());
- return p;
- });
W: 6
S: 6
W: 4
S: 4
W: 3
W: 2
S: 2
W: 9
W: 1
W: 7
W: 8
S: 8
W: 5
O: 6
O: 4
O: 2
O: 8
2
4
6
8