Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception on list.remove() even numbers

Tags:

c#

I have a list of numbers and I’d like to remove all the even ones. I think my code is right:

System.Collections.Generic.List<int> list = ...
foreach (int i in list)
{
  if (i % 2 == 0)
    list.Remove(i);
}

but when I run it I get an exception. What am I doing wrong?

like image 432
user1100941 Avatar asked Feb 12 '26 15:02

user1100941


2 Answers

You can't modify a collection in a foreach loop, that being said, you can't remove an item from a list that you're iterating over in a foreach loop.

Instead of the foreach loop, just use this single line of code:

list.RemoveAll(i => i % 2 == 0);
like image 165
Gabe Avatar answered Feb 15 '26 04:02

Gabe


You cannot modify the collection during a foreach loop. A foreach loop uses an enumerator to loop through the collection, and when the collection is modified this is what happens to the enumerator:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

You can use a regular for loop.

for (int i = 0; i < list.Count; i++)
{
    int n = list[i];
    if (n % 2 == 0)
    {
        list.RemoveAt(i--);
    }
}
like image 21
Marlon Avatar answered Feb 15 '26 05:02

Marlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!