Reputation: 35621
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();}
?
Upvotes: 22
Views: 27840
Reputation: 421978
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.
Upvotes: 14
Reputation: 616
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();
}
Upvotes: 35
Reputation: 68667
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.
Upvotes: 0