使用带有自定义谓词的 List.Find 有点麻烦
我有一个功能可以做到这一点
private function test ()
Dim test As Integer = keys.Find(AddressOf FindByOldKeyAndName).NewKey
这是谓词的功能
Private Shared Function FindByOldKeyAndName(ByVal k As KeyObj) As Boolean
If k.OldKey = currentKey.OldKey And k.KeyName = currentKey.KeyName Then
Return True
Else
Return False
End If
End Function
这样做意味着我必须在类中有一个共享的“currentKey”对象,并且我知道必须有一种方法可以传递我感兴趣的 CurrentKey 值(即键名和旧键)
理想情况下,我想用类似的东西来称呼它
keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))
但是,当我这样做时,会出现编译器错误。
我如何调用此方法并传递值?
最佳答案
您可以使用 VS2008 及更高版本中可用的 lambda 表达式彻底解决此问题。一个愚蠢的例子:
Sub Main()
Dim lst As New List(Of Integer)
lst.Add(1)
lst.Add(2)
Dim toFind = 2
Dim found = lst.Find(Function(value As Integer) value = toFind)
Console.WriteLine(found)
Console.ReadLine()
End Sub
对于早期版本,您必须将“currentKey”设置为您类(class)的私有(private)字段。检查我的代码 this thread以获得更清洁的解决方案。
关于VB.Net 列表.查找。将值传递给谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655793/