Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - Remove from a List<T> within a 'foreach' loop

I have code that I want to look like this:

List<Type> Os;  ...  foreach (Type o in Os)     if (o.cond)         return;  // Quitting early is important for my case!     else         Os.Remove(o);  ... // Other code 

This doesn't work, because you cannot remove from the list when you are inside a foreach loop over that list:

Is there a common way to solve the problem?

I can switch to a different type if needed.

Option 2:

List<Type> Os;  ...  while (Os.Count != 0)      if (Os[0].cond)          return;      else          Os.RemoveAt(0);  ... // Other code 

Ugly, but it should work.

like image 394
BCS Avatar asked May 06 '09 22:05

BCS


People also ask

Can I remove item from List in forEach C#?

You can't use . Remove(element) inside a foreach (var element in X) (because it results in Collection was modified; enumeration operation may not execute.

How do I remove an item from a forEach?

To remove element from array in forEach loop with JavaScript, we can use the array splice method. const review = ["a", "b", "c", "b", "a"]; review. forEach((item, index, arr) => { if (item === "a") { arr. splice(index, 1); } });

Can we remove element from List while iterating?

Even though java. util. ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.


2 Answers

You can iterate through the list backwards:

for (int i = myList.Count - 1; i >= 0; i--) {     if (whatever) myList.RemoveAt(i); } 

In response to your comment about wanting to quit when you find an item that you're NOT removing, then just using a while loop would be the best solution.

like image 160
Jon B Avatar answered Sep 19 '22 03:09

Jon B


You should never remove anything from a collection you are iterating over while inside of a foreach loop. It's basically like sawing the branch you are sitting on.

Use your while alternative. It is the way to go.

like image 31
User Avatar answered Sep 18 '22 03:09

User