Common Linq / Standard Query Operator mistakes/mis-steps?

后端 未结 4 1086
感动是毒
感动是毒 2021-01-03 09:30

For programmers that do not come from a functional programming background, are there an mistakes to avoid?

4条回答
  •  渐次进展
    2021-01-03 10:06

    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.

提交回复
热议问题