Re: Newbie - delete item from collection

Chris Anderson <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
> 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.
> 

Imagine the items with index 0 and 1 are both >90 and step through the
code in your mind.

After the item with index 0 has been deleted, the item with index 1 now
has an index of 0 - so when you move to the next item (index 1), you've
skipped one.

Two solutions :
1. only increment idx when you do not delete one
2. start from _someList.Count and work towards index 0

Chris

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