Re: Newbie - delete item from collection
Eddie Lascu <[email protected]>
| Newsgroups | gmane.comp.windows.devel.dotnet.advanced |
|---|---|
| Organization | IBI Group |
| Message-ID | <[email protected]> |
Try this one instead:
for (int idx = 0; idx < _someList.Count; )
{
if (_someList[idx].ErrorCode > 90)
_someList.RemoveAt(idx);
else
idx++;
}
In your original code, you are skipping nodes. Imagine you deleted node with
index "n". The node that was previously "n+1" becomes now "n". You increment
"idx" and move it from "n" to "n+1", thinking that you took care of node
"n". The problem is that after you have deleted node "n" a new node becomes
"n" and you are skipping that. In my fix, you only increment "idx" when
there is no need to delete. If you delete, you keep your index to the same
position and next iteration you are checking a new node.
Cheers,
Eddie
-----Original Message-----
From: Discussion of advanced .NET topics.
[mailto:[email protected]] On Behalf Of Lars Zeb
Sent: Monday, November 17, 2008 3:27 PM
To: [email protected]
Subject: [ADVANCED-DOTNET] Newbie - delete item from collection
I have defined a and populated a generic list with 3rd party software.
After it is created, I need to remove all items with an errorcode value >
90.
Is this supposed to work?
for (int idx = 0; idx < _someList.Count; idx++)
{
if (_someList[idx].ErrorCode > 90)
_someList.RemoveAt(idx);
}
After I "removed" items with ErrorCode> 90, the list still contained some
items with ErrorCodes over 90.
Or should I create a new list and add items to it from the old list with
ErrorCodes <=90?
Thanks, Lars
===================================
View archives and manage your subscription(s) at
http://peach.ease.lsoft.com/archives
===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives