Saif Khan Saif Khan - 8 months ago 35 Question

Search for Object in Generic List

Is it possible to search for an object by one of its properties in a Generic List?

Public Class Customer

Private _id As Integer

Private _name As String

Public Property ID() As Integer
Return _id
End Get
_id = value
End Set
End Property

Public Property Name() As String
Return _name
End Get
_name = value
End Set
End Property

Public Sub New(id As Integer, name As String)
_id = id
_name = name
End Sub

End Class

Then loading and searching

Dim list as new list(Of Customer)

list.Add(New Customer(1,"A")

list.Add(New Customer(2,"B")

How can I return customer object with id =1? Does this have to do with the "Predicate" in Generics?

Note: I am doing this in VB.NET.


Yes, this has everything to do with predicates :)

You want the Find(Of T) method. You need to pass in a predicate (which is a type of delegate in this case). How you construct that delegate depends on which version of VB you're using. If you're using VB9, you could use a lambda expression. (If you're using VB9 you might want to use LINQ instead of Find(Of T) in the first place, mind you.) The lambda expression form would be something like:

list.Find(function(c) c.ID = 1)

I'm not sure if VB8 supports anonymous methods in the same way that C# 2 does though. If you need to call this from VB8, I'll see what I can come up with. (I'm more of a C# person really :)