🤔

InvalidOperationException: Collection was modified#

When iterating over a collection using a foreach loop you are using an iterator that maintains the state of that loop.
Modifying the collection while looping like this will cause the iterator to become invalid, so an exception is thrown.

foreach (var item in collection)
{
    if (condition)
        collection.Remove(item); // InvalidOperationException.
}

Resolution#

I am using a List:#

I am using another collection type:#