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?
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);
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--);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With