加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:30:03 所属栏目:百科 来源:网络整理
导读:我有以下设置: Class A property x as string property y as int property z as StringEnd ClassClass CollOfA inherits List(Of A)End Class 我想要的是集合中的Item属性,我可以说: dim c as new CollOfAc.item("this",2,"that") 我试过在CollOfA中实现以
我有以下设置:

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 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 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","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有点生锈.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读