Search for Object in Generic List

前端 未结 4 1707
生来不讨喜
生来不讨喜 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: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.

提交回复
热议问题