I'm wondering why List<T>.ForEach(Action<T>)
exists.
Is there any benefit/difference in doing :
elements.ForEach(delegate(Element element){ element.DoSomething(); });
over
foreach(Element element in elements) { element.DoSomething();}
?
I'm wondering why List<T>.ForEach(Action<T>)
exists.
Is there any benefit/difference in doing :
elements.ForEach(delegate(Element element){ element.DoSomething(); });
over
foreach(Element element in elements) { element.DoSomething();}
?
You can use lambdas which make the code more consise.
elements.ForEach( e => e.DoSomething() );
It also eliminates if
statements:
elements.Where(e => e > 3).ForEach( e => e.DoSomething() );
compared to
foreach(Element element in elements)
{
if (element > 3)
element.DoSomething();
}
It is a more convenient way/shorthand to execute an action on the items in the list, MoreLinq extends this functionality for all that implement IEnumerable.
It's very likely to be faster (you shouldn't choose one over the other merely because of the small performance benefits, unless you're dealing with computationally heavy number crunching or graphics application and you need to get the most out of processor cycles) and you can pass delegates directly to it which may be convenient in some cases:
list.ForEach(Console.WriteLine); // dumps the list to console.
One key difference is with the .ForEach method you can modify the underlying collection. With the foreach syntax you'll get an exception if you do that. Here's an example of that (not exactly the best looking but it works):
static void Main(string[] args) {
try {
List<string> stuff = new List<string>();
int newStuff = 0;
for (int i = 0; i < 10; i++)
stuff.Add(".");
Console.WriteLine("Doing ForEach()");
stuff.ForEach(delegate(string s) {
Console.Write(s);
if (++newStuff < 10)
stuff.Add("+"); // This will work fine and you will continue to loop though it.
});
Console.WriteLine();
Console.WriteLine("Doing foreach() { }");
newStuff = 0;
foreach (string s in stuff) {
Console.Write(s);
if (++newStuff < 10)
stuff.Add("*"); // This will cause an exception.
}
Console.WriteLine();
}
catch {
Console.WriteLine();
Console.WriteLine("Error!");
}
Console.ReadLine();
}