在通用列表中搜索对象 [英] Search for Object in Generic List
问题描述
公共类Customer $ b是否可以通过Generic List中的某个属性搜索对象?
$ b私人_id作为整数
私人_作为字符串
公共财产ID()作为整数
获得
返回_id
结束获取
Set
_id = value
End Set
End Property
公共属性Name()As String
Get
返回_name
结束获取
Set
_name = value
结束Set
End Property
Public Sub New(id As Integer, name As String)
_id = id
_name = name
End Sub
End Class
然后加载并搜索
list.Add(新客户(1,A)
list.Add(新客户(2,B)
如何返回id = 1的客户对象?这是否与泛型中的谓词有关?
注意:我在VB.NET中做这个。
是的,这与谓词有关:
你想要 Find(Of T)方法。你需要传入一个谓词(在这种情况下它是一种委托类型)。您如何构建该委托取决于您使用的是哪个版本的VB。如果你使用VB9,你可以使用lambda表达式。 (如果你使用的是VB9,你可能想首先使用LINQ而不是Find(Of T),请注意。)lambda表达式的形式如下所示:
list.Find(function(c)c.ID = 1)
我不确定VB8是否支持与C#2相同的匿名方法。如果你需要从VB8调用这个,我会看看我能想出什么。 (我更像是一个C#人:)
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.
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 :)
这篇关于在通用列表中搜索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!