I am trying to iterate over a collection of items, perform an action and then remove the item at the current index.
The way I have this implemented currently is like so:
foreach (CormantRadPane pane in GetPanes().ToList())
{
pane.Clear();
StateManager.Remove(pane);
LayoutManager.Instance.RegisteredPanes.Remove(pane);
Items.Remove(pane);
}
By calling ToList I create a copy of the collection, but maintain a reference to each object in the first collection. This allows me to iterate over the collection returns from GetPanes without 'technically' modifying the collection.
This is clearly prone to some seriously hard to track down bugs. What is the standard way of performing such logic in a clean manner, but that also is more clear about the intriciaces of what is occurring?
I did some looking around and saw such things as using a for loop and going backwards through the list, but that just seems really bulky. My feelings are about the same with keeping a second list of items "to remove" and then iterating through that list after the first loop has finished, removing each object found in the second list.
How do you handle it? Thanks.