对于程序员不来自函数式编程背景,是否有一个失误,以避免?
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.