C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example: We create a List of 3 integers with a list initializer. We then enter a foreach-loop over the list.
Initialize ListForeach: This loop iterates over each item in the list. We call the Remove method, and it tries to modify the collection during the loop.
C# program that causes InvalidOperationException
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int>() { 10, 20, 30 };
// Try to remove an element in a foreach list.
foreach (int value in list)
{
Console.WriteLine("ELEMENT: {0}", value);
list.Remove(value);
}
}
}
Output
ELEMENT: 10
Unhandled Exception: System.InvalidOperationException:
Collection was modified; enumeration operation may not execute.
at System.ThrowHelper. ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections. Generic.List`1.Enumerator.MoveNextRare()
at System.Collections. Generic.List`1.Enumerator.MoveNext()
at Program.Main()...
Note: We are changing the elements in the collection while looping over it with foreach.
Info: An enumerator has to store some data indicating its current position. This is how the foreach loop is implemented.
RemoveAt: This is another method we could call. It will accept the index of the item we want to remove—it might be faster.
List RemoveRemoveAll: This might be the best way to remove items from a List without causing an exception. RemoveAll() receives a lambda.
RemoveAllExample: This program removes all elements in the list where the value is equal to 20.
C# program that uses Remove in for-loop
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int>() { 10, 20, 30 };
// Remove elements from the list in a for-loop.
for (int i = 0; i < list.Count; i++)
{
int value = list[i];
// Remove if value is 20.
if (value == 20)
{
list.Remove(value);
}
}
// Write list after element removed.
foreach (int value in list)
{
Console.WriteLine("ELEMENT: {0}", value);
}
}
}
Output
ELEMENT: 10
ELEMENT: 30