Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I use List<T>.ForEach over a native foreach loop?

Are there advantages to either approach? If I need to traverse List items and perform an action on each one, should I use the traditional foreach loop mechanism or move on to List.ForEach?

Matthew Podwysocki @ CodeBetter.com wrote an interesting article about the anti-for campaign. This got me thinking about the problem a loop is trying to solve. In this article, Matthew argues that explicit loop structures make you think about the 'how' instead of the 'what'.

What are some good reasons to use one over the other (if there are any)?

like image 218
Jordan Parmer Avatar asked Nov 29 '22 20:11

Jordan Parmer


1 Answers

For one thing, you'd use it if you'd been passed the delegate to apply for whatever reason. For example, you might create your own list, populate it etc and then apply a delegate to each entry. At that point, writing:

list.ForEach(action);

is simpler than

foreach (Item item in list)
{
    action(item);
}
like image 190
Jon Skeet Avatar answered Dec 06 '22 02:12

Jon Skeet