delete element of collection being iterated

  • Thread starter Thread starter Michal Januszczyk
  • Start date Start date
M

Michal Januszczyk

Hello.

Sometimes I encounter the following problem:

foreach( element of some collection)
{
delete this element;
}

of course, the runtime would not allow to modify
the collection whilst executing loop through
its elements.

I often happen to write solutoin to this problem
by myself, but i am curious if there is some
design pattern how to handle such a situation
(the need to delete element of collection being ierated
through)

Thaks for answer
Michal Januszczyk
 
One trick is to use "for(){}" backward, insteadof "foreach(){}":

for (int i=myCollection.Count-1; i>=0; i--)
{
myCollection.RemoveAt(i)
//Or your own Delete(i)/Remove(i) method, because if you remove item
//from a collection backward, remaining item's index will not change
}
 
Hi,

I also faced this problem and incorporated the following
solution for the same.

// Create a Hashtable and clone the existing HashTable
(accessible through the InnerHashtable property of the
types derived from the DictionaryBase class).

System.Collections.Hashtable LocalHashTable =
(System.Collections.Hashtable)this.InnerHashtable.Clone();

// Create an IEnumerator type instance, so as to traverse
the collection.

System.Collections.IEnumerator KeysEnumerator =
LocalHashTable.GetEnumerator();

// Finally traverse the collection
while (KeysEnumerator.MoveNext())
{
// Now you can manipulate the collection.
this.Dictionary.Remove(OldCellKey);
}



Regards,
Puneet Taneja
 
Back
Top