通过值x,y和z在List(Of T)中查找项目

Dea*_*ean 3 vb.net generics

我有以下设置:

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

End Class

Class CollOfA
    inherits List(Of A)

End Class
Run Code Online (Sandbox Code Playgroud)

我想要的是集合中的Item属性,我可以说:

dim c as new CollOfA
c.item("this", 2, "that")
Run Code Online (Sandbox Code Playgroud)

我试过在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
Run Code Online (Sandbox Code Playgroud)

我知道谓词,但我正在努力设置谓词的标准(即传递x,y和z).

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

Dav*_*ter 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
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建一个PredicateParameter类来保存您的参数,以及一个用于执行过滤器的委托方法.我在MSDN评论中看到了这一点 - 这是链接.这是班级:

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
Run Code Online (Sandbox Code Playgroud)

这是使用它的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
Run Code Online (Sandbox Code Playgroud)

最后,这是一个测试它的控制台运行器.

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
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助.可能有更优雅的方式来做到这一点,但我没有看到一个.(顺便说一句,我通常使用C#,所以我的VB.NET有点生锈.)