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
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();
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!
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.