using System;
using System.Linq;
static class Program
{
static double Square(double n)
{
Console.WriteLine("Computing Square(" + n + ")...");
return Math.Pow(n, 2);
}
public static void Main()
{
int[] numbers = { 1, 2, 3 };
var query =
from n in numbers
select Square(n); // query只是一个语句,下面的foreach才执行内容
foreach (var n in query)
Console.WriteLine(n); // 逐个执行Square(n);方法
for (int i = 0; i < numbers.Length; i++)
numbers[i] = numbers[i] + 10;
Console.WriteLine("- Collection updated -");
foreach (var n in query)
Console.WriteLine(n);
Console.ReadKey();
}
}
执行结果
Computing Square(1)...
1
Computing Square(2)...
4
Computing Square(3)...
9
- Collection updated -
Computing Square(11)...
121
Computing Square(12)...
144
Computing Square(13)...
169
同样的query,下面的却变了。query只是一个静态的存储语句。
当foreach的时候,才逐个执行查询结果。
再看小例子
using System;
using System.Diagnostics;
using System.Linq;
static class Program
{
public static void Main()
{
var processes =
Process.GetProcesses()
.Where(process => process.WorkingSet64 > 20 * 1024 * 1024)
.OrderByDescending(process => process.WorkingSet64)
.Select(process => new {
process.Id,
Name = process.ProcessName
});
foreach (var item in processes)
Console.WriteLine(item.Name);
Console.ReadKey();
}
}
通过图解,能够更加清晰它的流程。
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/7019392.html,如需转载请自行联系原作者