gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:13:34 25 4
gpt4 key购买 nike

我有以下设置:

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 类来保存您的参数以及一个用于执行过滤器的委托(delegate)方法。我在 MSDN 评论中看到了这个 - 这是 link .这是类(class):

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 有点生疏。)

关于vb.net - 通过值 x、y 和 z 在 List(Of T) 中查找项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3336662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com