Re: generic List<>
Efran Cobisi <[email protected]>
| Newsgroups | gmane.comp.windows.devel.dotnet.cx |
|---|---|
| Organization | QBGROUP SpA |
| Message-ID | <[email protected]> |
That's right. I assumed he wanted to stay with the IEnumerator iterator...
Btw the fastest way to remove the items from a List<T> is, as suggested
by Roberto, using the RemoveAll method. It really cuts down the lines of
code you would want to type and, under the cover, does not create any
new reference to existing objects: it just works against the inner array
mantained by the List<T>.
In our example:
myObjects.RemoveAll(delegate(MyObject mo) { return mo.CanBeRemoved; });
Efran Cobisi, cobisi.com
Peter Ritchie wrote:
> Only removal of collection items while using the IEnumerator interface is
> not supported. You can enumerate a collection in other ways, without
> creating a new collection and copying a bunch of references.
>
> For example:
> for (int i = (myObjects.Count - 1); i >= 0; --i)
> {
> myObjects mo = myObjects[i];
> if (mo.CanBeRemoved)
> {
> myObjects.Remove(mo);
> }
> }
>
> On Wed, 30 Aug 2006 16:06:31 +0200, Efran Cobisi <[email protected]>
> wrote:
>
>
>> 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
>
>> ===================================
>> This list is hosted by DevelopMentor® http://www.develop.com
>>
>> View archives and manage your subscription(s) at
>>
> http://discuss.develop.com
>
> You're on
>
> ===================================
> This list is hosted by DevelopMentor® http://www.develop.com
>
> View archives and manage your subscription(s) at http://discuss.develop.com
>
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com