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 doesn't specify what algorithm they're using to remove the item.
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.