常见的LINQ /标准查询操作错误/错误的步骤? [英] Common Linq / Standard Query Operator mistakes/mis-steps?
本文介绍了常见的LINQ /标准查询操作错误/错误的步骤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于程序员不来自函数式编程背景,是否有一个失误,以避免?
For programmers that do not come from a functional programming background, are there an mistakes to avoid?
推荐答案
人们往往会犯的最大错误是误解了懒惰和评价规则LINQ查询:
The biggest mistake people tend to make is to misunderstand the laziness and evaluation rules for a LINQ query:
查询是懒惰:他们不执行,直到你遍历他们:
Queries are lazy: they are not executed until you iterate over them:
// This does nothing! No query executed!
var matches = results.Where(i => i.Foo == 42);
// Iterating them will actually do the query.
foreach (var match in matches) { ... }
此外,结果不被缓存。他们在每次迭代他们的时间计算:
Also, results are not cached. They are computed each time you iterate over them:
var matches = results.Where(i => i.ExpensiveOperation() == true);
// This will perform ExpensiveOperation on each element.
foreach (var match in matches) { ... }
// This will perform ExpensiveOperation on each element again!
foreach (var match in matches) { ... }
底线:什么时候你的查询被执行
Bottom line: know when your queries get executed.
这篇关于常见的LINQ /标准查询操作错误/错误的步骤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文