Re: generic List<>

Peter Osucha <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <[email protected]>
Ahhh, simple enough.  Thanks, Efran.


> -----Original Message-----
> From: Discussion relating to the specifics of the C# and
> Managed C++ languages [mailto:[email protected]]
> On Behalf Of Efran Cobisi
> Sent: Wednesday, August 30, 2006 10:07 AM
> To: [email protected]
> Subject: Re: [DOTNET-CX] generic List<>
>
> Nope. By design you are not allowed to make any changes to
> the collection you are iterating.
> The workaround for this depends on the situation. For most
> scenarios, you could just copy the references of the objects
> you wish to be deleted in another collection and then, while
> iterating the latter, delete these objects from the former.
>
> List<myObject> myTemp = new List<myObject>();
>
> foreach (MyObject mo in myObjects)
> {
>     if (mo.CanBeRemoved==true)
>         myTemp.Add(mo);
> }
>
> foreach (MyObject mo in myTemp)
>         myObjects.Remove(mo);
>
>
> HTH
>
> Efran Cobisi, cobisi.com
>
> Peter Osucha wrote:
> > I have a generic List<myObject> collection 'myObjects'.  MyObject
> > instances have a bool property 'CanBeRemoved'.
> >
> > But apparently, it is invalid to
> >
> > foreach (MyObject mo in myObjects)
> > {
> >     if (mo.CanBeRemoved==true) myObjects.Remove(mo); }
> >
> > Is there a way to remove items from such collection while looping
> > through the collection?
> >
> > Peter

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.