Issue:
I have the following code:
foreach(var ItemA in GenericListInstanceB)
{
ItemA.MethodThatCouldRemoveAnyItemInGenericListInstanceB();
}
Obviously i get an error.
What i want to do is change GenericListInstanceB
to a class i create, that keeps track of items it should remove. Then, when the loop is finished, it removes them all. Same with adding items.
This is fine, i can create a class that has an internal list, and a list of items to add and items to remove. Then another method called AddRemovePendingItems
that actually 'updates' the list (removes and adds items accordingly). The tricky part is getting that method to be called automatically.
Ideas: Maybe looking at when GetEnumerator
is called? Maybe doing something clever with IDisposable
?
Question: How do i know when the for loop exits and we've finished iterating over my collection class so i can call my AddRemovePendingItems
method?, particularly if the loop break's early?
Note I want to avoid any unnecessary copying as i want to eliminate/minimise garbage collection so i can't just iterate over a copy/make a new copy or anything like that.