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

前端之家收集整理的这篇文章主要介绍了VB.Net List.Find.将值传递给谓词前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用List.Find与自定义谓词有点麻烦

我有一个这样做的功能

  1. private function test ()
  2. Dim test As Integer = keys.Find(AddressOf FindByOldKeyAndName).NewKey

这里是谓词的功能

  1. Private Shared Function FindByOldKeyAndName(ByVal k As KeyObj) As Boolean
  2. If k.OldKey = currentKey.OldKey And k.KeyName = currentKey.KeyName Then
  3. Return True
  4. Else
  5. Return False
  6. End If
  7.  
  8.  
  9. End Function

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

理想情况下,我想把它称为
keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))

但是当我这样做我会得到编译错误.

我如何称这种方法并传递值?

您可以使用VS2008及以上版本的lambda表达式清理该问题.一个愚蠢的例子:
  1. Sub Main()
  2. Dim lst As New List(Of Integer)
  3. lst.Add(1)
  4. lst.Add(2)
  5. Dim toFind = 2
  6. Dim found = lst.Find(Function(value As Integer) value = toFind)
  7. Console.WriteLine(found)
  8. Console.ReadLine()
  9. End Sub

对于早期版本,您必须使“currentKey”成为您类的私有字段.检查我的代码this thread为一个更清洁的解决方案.

猜你在找的VB相关文章