Search for Object in Generic List

前端 未结 4 1704
生来不讨喜
生来不讨喜 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)
    

提交回复
热议问题