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