LINQ equivalent of foreach for IEnumerable

后端 未结 22 2252
夕颜
夕颜 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条回答
  •  渐次进展
    2020-11-21 23:32

    Keep your Side Effects out of my IEnumerable

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

    As others have pointed out here and abroad LINQ and IEnumerable methods are expected to be side-effect free.

    Do you really want to "do something" to each item in the IEnumerable? Then foreach is the best choice. People aren't surprised when side-effects happen here.

    foreach (var i in items) i.DoStuff();
    

    I bet you don't want a side-effect

    However in my experience side-effects are usually not required. More often than not there is a simple LINQ query waiting to be discovered accompanied by a StackOverflow.com answer by either Jon Skeet, Eric Lippert, or Marc Gravell explaining how to do what you want!

    Some examples

    If you are actually just aggregating (accumulating) some value then you should consider the Aggregate extension method.

    items.Aggregate(initial, (acc, x) => ComputeAccumulatedValue(acc, x));
    

    Perhaps you want to create a new IEnumerable from the existing values.

    items.Select(x => Transform(x));
    

    Or maybe you want to create a look-up table:

    items.ToLookup(x, x => GetTheKey(x))
    

    The list (pun not entirely intended) of possibilities goes on and on.

提交回复
热议问题