Remove an element while enumerating through a collection

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..
 
A

Alvin Bruney [MVP]

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
 
E

Edward Diener

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 ?
 
G

Giedrius

Actuall'y you can write your custom Collection with custom Enumerator. And
use any logic you want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top