foreach vs someList.ForEach(){}

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.

Leave a Comment