LINQ + Foreach vs Foreach + If

前端 未结 4 1606
醉梦人生
醉梦人生 2020-12-02 09:55

I need to iterate over a List of objects, doing something only for the objects that have a boolean property set to true. I\'m debating between this code

for         


        
4条回答
  •  隐瞒了意图╮
    2020-12-02 10:25

    Most Linq operators such as Where are implemented to support deferred and lazy execution. In your example, the list will be iterated over only once because the enumerator sitting behind the IEnumerable returned by Where will enumerate the list until it finds an item matching the predicate, yields it and will only continue when it is asked for the next element.

    From a code perspective, I'd prefer the variant using where, although it could be argued you could declare a local for parameters.Where(p => p.Condition).

    Jon Skeet's Edulinq series comes highly recommended, reading some bits of this should help you with your understanding of LINQ operators.

提交回复
热议问题