答案 0 :(得分:6)
我想出了两种方法来完成你的问题。一种方法是使用LINQ查询语法进行过滤;第二个使用自定义对象来保存谓词参数,然后使用该对象来执行过滤器。
在Item属性中使用LINQ语法:
Default Public Overridable Shadows ReadOnly Property Item(ByVal x As String, ByVal y As Integer, ByVal z As String) As IEnumerable(Of A)
Get
Return (From theA In Me
Where (theA.x = x And theA.y = y And theA.z = z)
Select theA)
End Get
End Property
另一种方法是创建一个PredicateParameter类来保存您的参数,以及一个用于执行过滤器的委托方法。我在MSDN评论中看到了这一点 - 这是link。这是班级:
Class PredicateParams
Public Sub New(ByVal theA As A)
Criteria = theA
End Sub
Public Property Criteria As A
Public Function IsMatch(ByVal theA As A) As Boolean
Return (theA.x = Criteria.x And theA.y = Criteria.y And theA.z = Criteria.z)
End Function
End Class
这是使用它的CollOfA类中的属性:
Public Overridable Shadows ReadOnly Property ItemPred(ByVal x As String, ByVal y As Integer, ByVal z As String) As IEnumerable(Of A)
Get
Dim predA As New A
predA.x = x
predA.y = y
predA.z = z
Dim pred As New PredicateParams(predA)
Return Me.FindAll(AddressOf pred.IsMatch)
End Get
End Property
最后,这是一个测试它的控制台运行器。
Sub Main()
Dim mycoll As New CollOfA()
For index = 1 To 100
Dim anA As New A()
anA.x = (index Mod 2).ToString()
anA.y = index Mod 4
anA.z = (index Mod 3).ToString()
mycoll.Add(anA)
Next
Dim matched As IEnumerable(Of A) = mycoll.Item("1", 3, "2")
Dim matched2 As IEnumerable(Of A) = mycoll.ItemPred("1", 3, "2")
Console.WriteLine(matched.Count.ToString()) 'output from first search
Console.WriteLine(matched2.Count.ToString()) 'output from second search (s/b same)
Console.ReadLine()
End Sub
希望这会有所帮助。可能有更优雅的方式来做到这一点,但我没有看到一个。 (顺便说一句,我通常使用C#,所以我的VB.NET有点生疏。)
答案 1 :(得分:1)
如果您的A类足够简单,您可以使用单行默认属性getter和List的Find方法,如下所示:
Public Class CollOfA
Inherits List(Of A)
Default Public Overloads ReadOnly Property Item(ByVal x As String, ByVal y As Integer, ByVal z As String) As A
Get
Return Find(Function(a As A) (((a.x = x) AndAlso (a.y = y)) AndAlso (a.z = z)))
End Get
End Property
End Class
我在Visual Studio 2008中这样做了,所以我不知道它在其他版本中是如何工作的。