Skip to main content
Sep 05, 2017

If you try to change collection (add or remove element) while you looping through it, the following error message could appear:

InvalidOperatioException was unhandled

Collection was modified; enumeration operation may not execute.

The message could be present in the following situation:

foreach (Item item in collection)
{
    if (item.expired == true)
    {
        collection.Remove(item);
    }
}

Updating collections is one the most common thing we do in our code so here is one way to avoid the issue. Use ToArray() method 

foreach (Item item in collection.ToArray())
{
    if (item.expired == true)
    {
        collection.Remove(item);
    }
}

When the collection is large compared to the number of updates being implemented it is probably best to create a seperate list to hold the edits and then enumerate them like in the following example:

List<Item> updates = new List<Item>();
 
foreach (Item item in collection)
{
    if (item.expired == true)
    {
        updates.Add(item);
    }
}
 
foreach (Item item in updates)
{
    collection.Remove(item);
}