对于没有函数式编程背景的程序员来说,有什么错误是需要避免的吗?
人们容易犯的最大错误是误解 LINQ 查询的惰性和评估规则:
查询是惰性的:在您迭代它们之前它们不会被执行:
// 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) { ... }
此外,结果不会被缓存。每次迭代它们时都会计算它们:
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) { ... }
底线:知道查询何时执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)