I'd like to do the equivalent of the following in LINQ, but I can't figure out how:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
What is the real syntax?
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
What is the real syntax?
There is an experimental release by Microsoft of Interactive Extensions to LINQ (also on NuGet, see RxTeams's profile for more links). The Channel 9 video explains it well.
Its docs are only provided in XML format. I have run this documentation in Sandcastle to allow it to be in a more readable format. Unzip the docs archive and look for index.html.
Among many other goodies, it provides the expected ForEach implementation. It allows you to write code like this:
Now we have the option of...
Of course, this opens up a whole new can of threadworms.
ps (Sorry about the fonts, it's what the system decided)
This "functional approach" abstraction leaks big time. Nothing on the language level prevents side effects. As long as you can make it call your lambda/delegate for every element in the container - you will get the "ForEach" behavior.
Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites)
this is a hack, and should not be used in any production code.
Yet another
ForEach
ExampleInspired by Jon Skeet, I have extended his solution with the following:
Extension Method:
Client:
. . .
Keep your Side Effects out of my IEnumerable
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.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.Perhaps you want to create a new
IEnumerable
from the existing values.Or maybe you want to create a look-up table:
The list (pun not entirely intended) of possibilities goes on and on.