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?
You could use the
FirstOrDefault()
extension, which is available forIEnumerable<T>
. By returningfalse
from the predicate, it will be run for each element but will not care that it doesn't actually find a match. This will avoid theToList()
overhead.For VB.NET you should use:
Many people mentioned it, but I had to write it down. Isn't this most clear/most readable?
Short and simple(st).
MoreLinq has
IEnumerable<T>.ForEach
and a ton of other useful extensions. It's probably not worth dependency just forForEach
, but there's a lot of useful stuff in there.https://www.nuget.org/packages/morelinq/
https://github.com/morelinq/MoreLINQ
There is no ForEach extension for
IEnumerable
; only forList<T>
. So you could doAlternatively, write your own ForEach extension method:
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.