Search for Object in Generic List

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

提交回复
热议问题