No, there isn't, unfortunately. (I think this question has been discussed before, but I can't find it currently.)
Due to some bizarre accident of history, the ForEach
method ended up on List<T>
, instead of IEnumerable<T>
, where it would make more sense, and because of backwards-compatiblity, this can never ever be fixed.
Ever since extension methods existed, adding a ForEach(this IEnumerable<T>, ...)
extension method was requested over and over again, but it is usually rejected because it would lead to confusing behavior: since instance methods are always selected before extension methods, this would mean that all IEnumerable
s get treated identically, except for List
s and they wouldn't allow such inconsistencies in the BCL.
As a result, pretty much every .NET project on the planet now starts off with exactly the code you described above:
namespace IEnumerableExtensions
{
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> xs, Action<T> f)
{
foreach (var x in xs) f(x);
}
}
}