Possible Duplicate:
LINQ equivalent of foreach for IEnumerable<T>
I'm wondering whether there is a method for IEnumerable like the following .Each() in the .Net library
var intArray = new [] {1, 2, 3, 4};
intArrary.Each(Console.WriteLine);
I know I can use a foreach
loop or easily write an extension method like this:
public static class EnumerableExtensions
{
public static void Each<T>(this IEnumerable<T> enumberable, Action<T> action)
{
foreach (var item in enumberable)
{
action(item);
}
}
}
But I'm hoping not to create my own method to mess up code if there is already such an extension method in the library. And something like .Each() (with a few overloadings which can take conditions as extra params) is heavily needed by programmers, and there should already be one. Am I correct?
Update
Ruby developers may recognize it as a .each() iterator. And that's what I hope to have in C#. Maybe C# can have more iterator methods like those in Ruby.
As others have said there is none built in on IEnumerable<T>
. 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<T>
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<T>(IEnumerable<T> enumerable,Action<T> action)
{
foreach(var item in enumerable) action(item);
}
public static void ForEach<T>(IEnumerable<T> enumerable,Action<T,int> action)
{
int index = 0;
foreach(var item in enumerable) action(item,index++);
}
I'd also include argument validation as these are public methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With