MilMike
MilMike

Reputation: 12831

How to remove Objects from List(Of myClass) by Object Value?

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

Answers (3)

vc 74
vc 74

Reputation: 38179

Persons.RemoveAll(person => person.Name == "Jamie")

in VB:

Persons.RemoveAll(Function(person) person.Name = "Jamie")

(Thanks Heinzi)

Upvotes: 11

Ed Swangren
Ed Swangren

Reputation: 124652

Well, you have a couple of options.

  1. 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.

  2. Persons.RemoveAll(Function(person) person.Name = "Jamie")

Upvotes: 1

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

It's just doing so:

Persons.Remove(Persons.Single(Function(person) person.Name = "Jamie"))

Upvotes: 3

Related Questions