Re: Newbie - delete item from collection

Geoff Taylor <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <002401c948f5$ffbd4030$ff37c090$@com>
I think the main problem with that code is that it 'skips' the item after
the removed one.

So if you have a list of A, B, C, and your loop removes A, B is skipped
(because of the incremented loop counter) and C is the next item checked.

(I'd also have expected it to throw an exception towards the end, because
there are no longer _someList.Count items in the list.)

Try reversing the loop so it starts at the end:

         for (int idx = _someList.Count - 1; idx >= 0; idx--)

That should sort out both issues.

Good luck,

			Geoff

-----Original Message-----
From: Discussion of advanced .NET topics.
[mailto:[email protected]] On Behalf Of Lars Zeb
Sent: 17 November 2008 20:27
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
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.