此linq查询是否在for-each循环的每次迭代中运行? [英] Does this linq query run on every iteration of the for-each loop?

查看:66
本文介绍了此linq查询是否在for-each循环的每次迭代中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在关于SO的另一个问题中,我用下面的代码回答,并评论说LINQ查询可能在for/each的每次迭代中都得到了评估.是真的吗?

In another question on SO I answered with code like the one below and got a comment that the LINQ-query probably was evaluated in every iteration of the for/each. Is that true?

我知道LINQ查询在其项被评估之前不会执行,因此这种迭代结果的方式似乎有可能使它在每次迭代中运行?

I know that LINQ-querys does not executes before its items is evaluated so it seems possible that this way to iterate the result can make it run on every iteration?

Dim d = New Dictionary(Of String, String)()    
d.Add("Teststring", "Hello")    
d.Add("1TestString1", "World")    
d.Add("2TestString2", "Test")    

For Each i As String In From e In d Where e.Value.StartsWith("W") Select e.Key
    MsgBox("This key has a matching value:" & i)    
Next

推荐答案

否...在foreach中,"GetEnumerator"仅(一次)被调用一次,以后将被使用.

NO... in a foreach, the "GetEnumerator" is called only once (ever), and that is used going forward.

我在这里发表了关于暂时存储结果集的声明...仅在某些情况下是正确的...并非如此,所以我将其取出.

I put a statement here about the result set being stored temporarily... that's only true for some cases... not this one, so I took it out.

请原谅这个命令过于冗长...但是我想显示您正在发生的事情...所以这是一个控制台应用程序:)

Please forgive this for being overly verbose... but I wanted to show you what is happening... so here's a Console app :)

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (string item in MyCustomEnumerator()
                .Where(item => item.StartsWith("abc")))
            {
            Console.WriteLine(item);
            }
        }

        static IEnumerable<string> MyCustomEnumerator()
        {
            Console.WriteLine(DateTime.Now);

            yield return "abc1";

            Console.WriteLine(DateTime.Now);

            yield return "abc2";

            Console.WriteLine(DateTime.Now);

            yield return "abc3";

            Console.WriteLine(DateTime.Now);

            yield return "xxx";
        }
    }
}

这将导致一个DateTime,然后是abc1,然后是DateTime,然后是abc2,然后是DateTime,然后是abc3,然后是DateTime.

This will result in a DateTime, then abc1, then a DateTime, then abc2, then a DateTime, then abc3, then a DateTime.

这篇关于此linq查询是否在for-each循环的每次迭代中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆