🤔

InvalidOperationException: Collection was modified#

Collection addition#

There are a couple of options for modifying collections when iterating.

Create a temporary copy of the collection before iterating over the copy.#

var copy = new CollectionType(collection);
foreach (var item in copy)
{
    if (condition)
        collection.Add(item);
}
information

CollectionType should be replaced with the type used to create the original collection.

Or:

Create a temporary collection used for removals after the loop.#

var additions = new List<ItemType>();
foreach (var item in collection)
{
    if (condition)
    {
        // Cache a deferred addition.
        additions.Add(item);
    }
}

// Apply the additions to the collection.
collection.AddRange(additions);
information

ItemType should be replaced with the type used to key additions.

information

To reduce the garbage collection impact of either of these methods you can use a pooled collection, like one retrieved from the built-in collection pools like ListPool, HashSetPool, or DictionaryPool.