There are a couple of options for modifying collections when iterating.
var copy = new CollectionType(collection);
foreach (var item in copy)
{
if (condition)
collection[key] = modification;
}CollectionType should be replaced with the type used to create the original collection.
Or:
var modifications = new List<(KeyType key, ItemType value)>();
foreach (var item in collection)
{
if (condition)
{
// Cache a deferred modification.
modifications.Add((key, modification));
}
}
// Apply modifications to the collection.
foreach (var pair in modifications)
{
collection[pair.key] = pair.value;
}KeyType should be replaced with the type used for values in your collection.
ItemType should be replaced with the type used to key modifications.
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.