Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items from a List(Of t) in vb.net failing

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.

like image 218
Cody C Avatar asked Dec 17 '09 16:12

Cody C


People also ask

How do I remove items from ListBox in Visual Basic?

You can use this method to remove a specific item from the list by specifying the index of the item to remove from the list. To specify the item to remove instead of the index to the item, use the Remove method. To remove all items from the list, use the Clear method.

How do you clear ListBox items control in VB net?

For removing an item in the ListBox, we simply type this syntax ComboBox1. Items. Remove(ListBox1. SelectedItem) .

How do I remove an item from an object list?

The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List.

How does C# list Remove work?

The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List.


1 Answers

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.

like image 72
Ryan Lundy Avatar answered Sep 23 '22 02:09

Ryan Lundy