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