Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        Get
            Return _id
        End Get
        Set
            _id = value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set
            _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.

like image 462
Saif Khan Avatar asked Oct 14 '08 06:10

Saif Khan


3 Answers

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 :)

like image 154
Jon Skeet Avatar answered Nov 03 '22 14:11

Jon Skeet


Generally you need to use predicates:

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

Private Function HasID1(ByVal c As Customer) As Boolean
    Return (c.ID = 1)
End Function

Dim customerWithID1 As Customer = list.Find(AddressOf HasID1)

Or with inline methods:

Dim customerWithID1 As Customer = list.Find(Function(p) p.ID = 1)
like image 43
Ozgur Ozcitak Avatar answered Nov 03 '22 16:11

Ozgur Ozcitak


You could also overload the equals method and then do a contains. like this

Dim list as new list(Of Customer)

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

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

list.contains(new customer(1,"A"))

the equals method then would look like this

public overrides function Equals(Obj as object) as Boolean
   return Me.Id.Equals(ctype(Obj,Customer).Id
end Function

Not tested but it should be close enough.

like image 1
chrissie1 Avatar answered Nov 03 '22 15:11

chrissie1