views:

566

answers:

4

I have a generic list that I'm removing items out of using List.Remove(Object). I have been removing items but whenever I get to the fifth item I'm removing it fails and does not remove it from the list. It doesn't seem to matter what I'm removing but everytime I try to remove five items it fails on the fifth item.

What could be causing this? Looking at the documentation for List(Of t).Remove, it doesnt specify what algorithm they're using to remove the item.

Thanks for any help.

Cody C

A: 

How many items are in your list? How are you removing them, just looping through? Keep in mind these are 0-based lists. If you're doing any sort of For loop with an integer it may not work as you're removing items.

Shawn Steward
A: 

If you are using for loop to remove elements, you should consider using the foreach, it is more suitable for collections, lists and numerable objects

jose
If he removes an element from the list in the middle of a foreach loop he'll get an `InvalidOperationException` as the collection was modified.
Dan Tao
+1  A: 

If you are using an indexed based method to remove items from the list and remember that the indexes of items after the one you remove will change by -1 as you remove the ones before it.

Jeffrey Hines
+1 - for what I'd wager is the correct answer despite the scant details in the question.
Joe
Which is why, if he's using an index-based method, he should be enumerating from the end of the list to the beginning.
Dan Tao
Or on each step he can *either* increment the loop variable *or* remove an item, but not both.
Kyralessa
+2  A: 

Remove is going to match based on calling .Equals on your objects. By default for a given object it'll only match the same object. If you want two objects with the same properties to be considered equal even if they're not the same object, you need to override the Equals method and put your logic there.

However, another good option is to use RemoveAll and pass in an anonymous delegate or a lambda expression with the criteria you're looking for. E.g.:

customers.RemoveAll(customer => customer.LastName.Equals(myCustomer.LastName));

Of course that only works if you really want to remove all the matching items, and/or if you're certain there will only be one that matches.

Kyralessa