Search for Object in Generic List

前端 未结 4 1694
生来不讨喜
生来不讨喜 2020-12-08 22:17

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 St         


        
相关标签:
4条回答
  • 2020-12-08 22:54

    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)
    
    0 讨论(0)
  • 2020-12-08 22:57

    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.

    0 讨论(0)
  • 2020-12-08 23:07

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

    0 讨论(0)
  • 2020-12-08 23:19

    If you are using .NET 3.5 this can be done with LINQ to Objects:

    How to: Query an ArrayList with LINQ

    If not, in .NET 2.0 you can use the Find method of the list.

    The idea is that you will need to provide an method that return true if a property of your object satisfies a certain condition.

    0 讨论(0)
提交回复
热议问题