LinQ:何时执行查询

时间:2012-09-28 07:13:54

标签: c#-3.0

根据此链接:http://msdn.microsoft.com/en-us/library/bb397906.aspx

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);
            }
        }
    }

}

它声明在通过foreach迭代数据之前不会执行查询。但是当我调试时,var(resultviews)的数据包含在执行foreach之前的结果值。为什么会这样?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

Linq正在使用一种名为Deferred Execution的东西。这是一篇很好的博客文章,解释了它: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);
            }

        }
    }
}

当您在Debugger.Break()语句中查看filteredNumbers时,您将看到以下内容:

Debug view of Linq Enumerable

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