VB.Net List.Find.将值传递给谓词 [英] VB.Net List.Find. Pass values to predicate

查看:36
本文介绍了VB.Net List.Find.将值传递给谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用带有自定义谓词的 List.Find 时遇到一些麻烦

Having a bit of trouble using the List.Find with a custom predicate

我有一个功能可以做到这一点

i have a function that does this

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 感兴趣的值(即键名和旧键)

by doing it this way means i have to have a shared "currentKey" object in the class, and i know there has to be a way to pass in the values i'm interested in of CurrentKey (namely, keyname, and oldkey)

理想情况下,我想这样称呼它keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))

ideally i'd like to call it by something like keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))

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

however when i do this i get compiler errors.

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

How do i call this method and pass in the values?

推荐答案

您可以使用 VS2008 及更高版本中提供的 lambda 表达式干净地解决此问题.一个愚蠢的例子:

You can cleanly solve this with a lambda expression, available in VS2008 and up. A silly example:

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"设为您的类的私有字段.在这个线程中检查我的代码 以获得更清洁的解决方案.

For earlier versions you'll have to make "currentKey" a private field of your class. Check my code in this thread for a cleaner solution.

这篇关于VB.Net List.Find.将值传递给谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆