user9381745
user9381745

Reputation:

Finding the Index of an Object in a List based on one of its Properties

What I have at the moment is a list of objects with a set of properties. As an example:

    Dim children As List(Of Child) = New List(Of Child)
    Dim child As Child = New Child

    child.FaveColor = "Blue"
    child.Pet = "Dog"
    child.SchoolID = "01893A"

    children.Add(child)

Later on I would like to be able to search my list for the index of said object based on, say, the unique school ID number for this child. I'm looking at FindIndex and IndexOf but all of the examples I've looked at involve searching the list based on the value of the object rather than one of its properties. It feels like it should be simple but I'm having quite a bit of trouble with it, so any help would be appreciated.

Upvotes: 3

Views: 1196

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

FindIndex is what you want. You provide a Predicate(Of T) delegate to that so you can use any condition(s) you like, e.g.

Dim dogOwnerIndex = children.FindIndex(Function(child) child.Pet = "Dog")

If you don't understand lambda expressions, you can use a named method:

Private Function ChildIsDogOwner(child As Child) As Boolean
    Return child.Pet = "Dog"
End Function

and create a delegate to that instead:

Dim dogOwnerIndex = children.FindIndex(AddressOf ChildIsDogOwner)

A Predicate(Of T) is just a delegate to a method that takes a T instance (T is the same as for the List, so Child in your case) and returns a Boolean. FindIndex basically loops through the items in the List and passes each one to the specified method and returns the index of the first item for which that method returns True.

Like I said, you can use any condition(s) you like in that predicate, e.g.

Dim blueLovingDogOwnerIndex = children.FindIndex(Function(child) child.Pet = "Dog" AndAlso
                                                                 child.FaveColor = "Blue")

Note that if you're doing an ad hoc search, i.e. using those conditions only once, then I'd suggest that a lambda is the way to go. If you're going to be doing the same search in multiple places, I'd suggest writing the method once only and using it in multiple places. Of course, you can write a lambda once too, e.g.

Private childIsDogOwner As Predicate(Of Child) = Function(child) child.Pet = "Dog"

and then use childIsDogOwner anywhere you need an appropriate delegate:

Dim dogOwnerIndex = children.FindIndex(childIsDogOwner)

Upvotes: 4

Related Questions