As others have said there is none built in on IEnumerable
. The Linq team was against it as per this post by Eric Lippert::
http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
There is a static method on Array.ForEach
and List
has an instance method. There is also in PLINQ foreach like statements, but be warned that they work in parallel and can lead to very bad performance for extremely simple actions.
Here is one such method in PLINQ: http://msdn.microsoft.com/en-us/library/dd383744.aspx
And here is a guide on PLINQ in general: http://msdn.microsoft.com/en-us/library/dd460688.aspx
While I can't find the exact article if you poke around in the ParrallelEnumerable section it gives warnings and tips as to how to improve the performance of using parallelism in code
If you want it, I suggest creating 2 versions, one that include indexer and one without. This can be quite useful and can save a select statement to acquire the index.
e.g.
public static void ForEach(IEnumerable enumerable,Action action)
{
foreach(var item in enumerable) action(item);
}
public static void ForEach(IEnumerable enumerable,Action action)
{
int index = 0;
foreach(var item in enumerable) action(item,index++);
}
I'd also include argument validation as these are public methods.