先看个简单的例子:
1 List list = new List () { 1, 2, 3, 4, 5, 6, 7 }; 2 var temp1 = from c in list where c > 3 select c; 3 var temp2 = (from c in list where c > 3 select c).ToList (); 4 list.Add(9); 5 Console.WriteLine("temp1:"); 6 foreach (var item in temp1) 7 { 8 Console.Write(item.ToString() + " "); 9 }10 Console.WriteLine("\ntemp2:");11 foreach (var item in temp2)12 {13 Console.Write(item.ToString() + " ");14 }
输出结果:
在延时求值的情况下,定义查询并没有立即查询,而是在访问查询结果的时候才会遍历原集合。对查询调用了ToList,ToArray等方法后,将会立即执行。从例子中可以看出。