Reputation: 6159
How do I remove an object from a list based on value, I'me getting an index out of range error
'A class called Person exists'
Dim PersonOne As New Person
PersonOne.name = "John"
PersonOne.age = 50
'Created a list to store them'
Dim MyList As New List(Of Person)
MyList.Add(PersonOne)
'Now to remove an object'
Dim ObjectToRemove As String = "John"
For Each item in MyList
If String.Compare(item.name, ObjectToRemove) = 0 Then
'How do I get the index to remove?'
End If
Next
Excuse the code, I bashed it out off the top of my head, my original code is a bit more convoluted. But the gist is I just want to compare a value, if it matches remove that . object from the List(Of).
Upvotes: 0
Views: 246
Reputation: 155055
Use the FindIndex
method which accepts a predicate delegate. You can pass a lambda function for the predicate delegate.
(Also, I think it's clearer to use String.Equals
with an explicit StringComparison
instead of using String.Compare(x,y) == 0
as it signals intent better).
Dim personOneHasThisIndex As Integer
personOneHasThisIndex = MyList.FindIndex( Function(p) p.name.Equals( ObjectToRemove, StringComparison.Ordinal ) )
If personOneHasThisIndx > -1 Then
' Always check if the result is -1, which means it doesn't exist
MyList.RemoveAt( personOneHasThisIndex )
End If
Note that List<T>.RemoveAt(Int32 index)
is inefficient because it has to move every element in the List (lists cannot have "empty" spaces). If you have a conceptual list you'll be adding and removing from a lot, consider using LinkedList
or a HashSet
(if the order of the elements doesn't matter) instead.
Upvotes: 2