No, there is no such extension method. List<T>
exposes a real method called ForEach
(which has been there since .NET 2.0).
views:
137answers:
5Nope, there isn't a built-in ForEach
extension method. It's easy enough to roll your own though:
public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
}
}
But why bother? As Eric Lippert explains in this blog post, the standard foreach
statement is more readable -- and philosophically more appropriate -- than a side-effecting ForEach
method:
myEnumerable.ForEach(x => Console.WriteLine(x));
// vs
foreach (var x in myEnumerable) Console.WriteLine(x);
There's some talk about it here. It's not build in to the frame work, but you can roll your own extension method and use it that way. This is probably your best bet from what I can tell.
I've been in the same situation.
public static class Extensions {
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
foreach (var item in source) {
action(item);
}
}
}
No there isn't. Eric Lippert talks about why this feature was omitted in his blog:
A number of people have asked me why there is no Microsoft-provided “ForEach” sequence operator extension method.
As a summary the two main reasons are:
- Using
ForEach
violates the functional programming principles that all the other sequence operators are based upon - no side-effects. - A
ForEach
method would add no new representational power to the language. You can easily achieve the same effect more clearly using a foreach statement.
IEnumerable do not have this extension method.
Read Eric Lippert's blog here for the reasoning behind it.
So if you need it, you will hav eto write it yourself :)