VB.Net List.Find.将值传递给谓词

Bet*_*033 10 vb.net

使用List.Find与自定义谓词有点麻烦

我有一个功能,这样做

private function test ()
    Dim test As Integer = keys.Find(AddressOf FindByOldKeyAndName).NewKey
Run Code Online (Sandbox Code Playgroud)

这是谓词的功能

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

通过这样做意味着我必须在类中有一个共享的"currentKey"对象,我知道必须有一种方法来传递我对CurrentKey感兴趣的值(即keyname和oldkey)

理想情况下,我想用类似的东西来称呼它 keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))

但是,当我这样做时,我得到编译器错误.

我如何调用此方法并传入值?

Han*_*ant 25

您可以使用在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
Run Code Online (Sandbox Code Playgroud)

对于早期版本,您必须将"currentKey"设为您班级的私有字段.检查此主题中的代码以获得更清晰的解决方案.