LINQ equivalent of foreach for IEnumerable

后端 未结 22 2273
夕颜
夕颜 2020-11-21 22:54

I\'d like to do the equivalent of the following in LINQ, but I can\'t figure out how:

IEnumerable items = GetItems();
items.ForEach(i => i.DoS         


        
22条回答
  •  -上瘾入骨i
    2020-11-21 23:20

    The purpose of ForEach is to cause side effects. IEnumerable is for lazy enumeration of a set.

    This conceptual difference is quite visible when you consider it.

    SomeEnumerable.ForEach(item=>DataStore.Synchronize(item));

    This wont execute until you do a "count" or a "ToList()" or something on it. It clearly is not what is expressed.

    You should use the IEnumerable extensions for setting up chains of iteration, definining content by their respective sources and conditions. Expression Trees are powerful and efficient, but you should learn to appreciate their nature. And not just for programming around them to save a few characters overriding lazy evaluation.

提交回复
热议问题