foreach vs someList.ForEach(){}

Bryce Fischer picture Bryce Fischer · Oct 22, 2008 · Viewed 240.6k times · Source

There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.

First type:

List<string> someList = <some way to init>
foreach(string s in someList) {
   <process the string>
}

Other Way:

List<string> someList = <some way to init>
someList.ForEach(delegate(string s) {
    <process the string>
});

I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...

Answer

user1228 picture user1228 · Oct 22, 2008

There is one important, and useful, distinction between the two.

Because .ForEach uses a for loop to iterate the collection, this is valid (edit: prior to .net 4.5 - the implementation changed and they both throw):

someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); }); 

whereas foreach uses an enumerator, so this is not valid:

foreach(var item in someList)
  if(item.RemoveMe) someList.Remove(item);

tl;dr: Do NOT copypaste this code into your application!

These examples aren't best practice, they are just to demonstrate the differences between ForEach() and foreach.

Removing items from a list within a for loop can have side effects. The most common one is described in the comments to this question.

Generally, if you are looking to remove multiple items from a list, you would want to separate the determination of which items to remove from the actual removal. It doesn't keep your code compact, but it guarantees that you do not miss any items.