LINQ& amp;IEnumerable& lt; String& gt;重新评估 [英] LINQ & IEnumerable<String> Re-evaluation

查看:40
本文介绍了LINQ& amp;IEnumerable& lt; String& gt;重新评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好

我编写了以下LINQ查询

I wrote the following LINQ query

 public static Func<String, IEnumerable<String>> ListaCorreccoes = (StrPalavra) =>
    {

        return (from StrTmp in ListaPossiveisCorreccoes(StrPalavra)
                from StrTmp2 in ListaPossiveisCorreccoes(StrTmp)
                where PalavraConhecida(StrTmp2)
                select StrTmp2).Distinct();            

    };

令我惊讶的是,它比使用两个 foreach cicle快得多.使用 ListaTmp = ListaCorreccoes("comutador"); 运行此函数后,其中 ListaTmp 的类型为 IEnumerable< String> ,我需要打印 ListaTmp 的基数使用

which, to my surprise, is much faster than using two foreach cicles. After running this function using ListaTmp = ListaCorreccoes("comutador");, where ListaTmp is of type IEnumerable<String>, I need to print ListaTmp's cardinality using

        Console.Write(">> Prima qualquer tecla para listar todas as " + ListaTmp.Count() + " correcções...");

并使用

foreach (String StrTmp in ListaTmp)
            Console.WriteLine(StrTmp);

但是,代码的最后一行和倒数第二行都导致ListaTmp,因此查询被重新评估 ,这非常奇怪,因为该变量被赋值为查询.为什么这段代码会有如此奇怪的行为?

However, both the last and prior-to-last lines of code cause ListaTmp and thus the query to be re-evaluated, which is so very strange since the variable is being assigned the result of the query. Why has this code such a strange behaviour?

非常感谢您.

推荐答案

这是因为LINQ使用延迟执行.请参阅 Charlie Calvert的有关LINQ和Deferred执行的文章.

That's because LINQ uses deferred execution. See Charlie Calvert's article on LINQ and Deferred Execution.

尝试以下方法:

var ListaTmp = ListaCorreccoes("comutador").ToList();

这一次枚举并将结果存储在 List< string> 中.

This enumerates once and stores the result in a List<string>.

您可能会发现Jon Skeet的文章很有用:

You might find Jon Skeet's articles useful:

这篇关于LINQ&amp; amp;IEnumerable&amp; lt; String&amp; gt;重新评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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