2012-09-28 46 views
0

按照此链接:http://msdn.microsoft.com/en-us/library/bb397906.aspx的LinQ:查询时将执行

namespace Linq 
{ 
    class IntroToLINQ 
    { 
     static void Main() 
     { 
      // The Three Parts of a LINQ Query: 
      // 1. Data source. 
      int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; 

      // 2. Query creation. 
      // numQuery is an IEnumerable<int> 
      var numQuery = 
       from num in numbers 
       where (num % 2) == 0 
       select num; 

      // 3. Query execution. 
      foreach (int num in numQuery) 
      { 
       Console.Write("{0,1} ", num); 
      } 
     } 
    } 

} 

它说,查询将不会被exeucted,直到数据通过foreach进行迭代。但是当我调试时,var(resultviews)的数据记忆包含执行foreach之前的结果值。为什么发生这种情况?

回答

0

因为您的调试器正在为您执行查询。

Linq正在使用称为延迟执行的东西。这里有一篇很好的博客文章解释它:LINQ and Deferred Execution

当你第一次执行迭代器时,查询被处理并执行(在内存中,数据库或其他方式)。你的调试器会为你做这个。

就拿下面的代码(可以在控制台应用程序粘贴):

using System; 
using System.Diagnostics; 
using System.Linq; 

namespace Stackoverflow 
{ 
    class Program 
    { 
     static void Main() 
     { 
      var numbers = Enumerable.Range(0, 100).ToList(); 

      var filteredNumbers = from n in numbers 
            where n > 50 
            select n; 

      Debugger.Break(); 

      foreach(int f in filteredNumbers) 
      { 
       Console.WriteLine(f); 
      } 

     } 
    } 
} 

当你看到filteredNumbers上Debugger.Break()语句,你会看到以下内容:

Debug view of Linq Enumerable

结果视图选项的值为:“展开结果视图将枚举IEnumerable”。这就是调试器中发生的事情。

0

当您使用调试器查看变量时,Visual Studio正在执行迭代器。这就是你看到结果的原因。

出于同样的原因,您不应该在监视窗口中放置i++,因为代码实际上是执行的。