Reputation: 12831
Is there a simple way to remove Objects from a List by using a specified value? I add 2 persons to a List, how can now I remove a person by a name without using any Loops? (if possible)
Public Class Form1
Public Persons As New List(Of Person)
Private Sub Test()
Persons.Add(New Person With {.Name = "Jamie", .Age = 99})
Persons.Add(New Person With {.Name = "Adam", .Age = 40})
'How to remove a person from the list having the name "Jamie" ?
'Persons.Remove(Name = "Jamie")... ???
End Sub
End Class
Public Class Person
Public Name As String
Public Age As Integer
End Class
Upvotes: 3
Views: 9359
Reputation: 38179
Persons.RemoveAll(person => person.Name == "Jamie")
in VB:
Persons.RemoveAll(Function(person) person.Name = "Jamie")
(Thanks Heinzi)
Upvotes: 11
Reputation: 124652
Well, you have a couple of options.
You can override the .Equals
method for your type and use the Name
property as the key to determine equivalence. This is probably not a good idea for a Person
class as multiple people may have the same name.
Persons.RemoveAll(Function(person) person.Name = "Jamie")
Upvotes: 1
Reputation: 64923
It's just doing so:
Persons.Remove(Persons.Single(Function(person) person.Name = "Jamie"))
Upvotes: 3