Remove an element while enumerating through a collection

  • Thread starter Thread starter Edward Diener
  • Start date Start date
E

Edward Diener

If I am enumerating through a collection, will removing the entry which is
my current one destroy my ability to keep enumerating the remaining elements
successfully. In my case the collection is a hybrid dictionary and while I
am enumerating the elements I want to remove the current one depending on
its value. Of course I know the technique of keeping a list of keys in a
separate array, to remove the appropriate ones after my enumeration has
finished, but I would like to know if this is necessary with .NET
collections or if I can remove while I am enumerating instead..
 
Actually, you can.

foreach(ListItem li in new Array(IteratingCollection)
{
if(li.Selected)
li.Remove();
}

roughly

--
Regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://www.lulu.com/owc
 
Alvin Bruney said:
Actually, you can.

foreach(ListItem li in new Array(IteratingCollection)
{
if(li.Selected)
li.Remove();
}

Huh ! What in the world is this doing ? How does li.Remove remove an item
from my original collection ?
 
Actuall'y you can write your custom Collection with custom Enumerator. And
use any logic you want.
 
Back
Top