我有以下设置:

Class A
      property x as string
      property y as int
      property z as String

End Class

Class CollOfA
    inherits List(Of A)

End Class

我想要的是集合中的Item属性,我可以说:
dim c as new CollOfA
c.item("this", 2, "that")

我已经尝试在CollOfA中实现以下内容:
Class CollOfA
    inherits List(Of A)

    Default Public Overridable Shadows ReadOnly Property Item(ByVal x As String, ByVal y As Integer, byval z as string)
        Get
            ' I want to do something like:
            ' ForEach item in me see if anything matches these three things

        End Get
    End Property
End Class

我了解谓词,但是我在努力设置谓词的标准(即传递x,y和z)方面感到困惑。

有没有人实现类似的东西?

最佳答案

我想出了两种方法来解决您的问题。一种方法是使用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有点生锈。)

10-08 11:28