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

10

使用自定义断言函数进行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 值(即 keyname 和 oldkey)。

理想情况下,我想通过类似以下方式调用它:keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))

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

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

4个回答

26

你可以使用 lambda 表达式来干净地解决这个问题,它在 VS2008 及更高版本中可用。以下是一个愚蠢的示例:

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"设置为类的私有字段。请查看此线程中的代码以获得更清晰的解决方案。


4

我有一个对象,它管理着一组唯一属性类型。

例如:

obj.AddProperty(new PropertyClass(PropertyTypeEnum.Location,value))
obj.AddProperty(new PropertyClass(PropertyTypeEnum.CallingCard,value))
obj.AddProperty(new PropertyClass(PropertyTypeEnum.CallingCard,value)) 
//throws exception because property of type CallingCard already exists

以下是用于检查属性是否已存在的代码:

Public Sub AddProperty(ByVal prop As PropertyClass)
    If Properties.Count < 50 Then
        'Lets verify this property does not exist
        Dim existingProperty As PropertyClass = _
            Properties.Find(Function(value As PropertyClass)
                Return value.PropertyType = prop.PropertyType
            End Function)

        'if it does not exist, add it otherwise throw exception
        If existingProperty Is Nothing Then
            Properties.Add(prop)
        Else
            Throw New DuplicatePropertyException("Duplicate Property: " + _
                         prop.PropertyType.ToString())
        End If

    End If
End Sub

2

我没有尝试在新版本的VB.Net中执行此操作,因为可能有更好的方法,但在旧版本中,我所知道的唯一方法是在类中设置共享成员以在调用前赋值。 网上有很多人创建小型实用程序类来包装它,使其看起来更加简洁。


0

我找到了一篇博客,其中提供了更好的“现实世界”上下文示例,并使用了良好的变量名称。

在列表中查找对象的关键代码如下:

      ' Instantiate a List(Of Invoice).
        Dim invoiceList As New List(Of Invoice)

        ' Add some invoices to List(Of Invoice).
        invoiceList.Add(New Invoice(1, DateTime.Now, 22))
        invoiceList.Add(New Invoice(2, DateTime.Now.AddDays(10), 24))
        invoiceList.Add(New Invoice(3, DateTime.Now.AddDays(30), 22))
        invoiceList.Add(New Invoice(4, DateTime.Now.AddDays(60), 36))

        ' Use a Predicate(Of T) to find an invoice by its invoice number.
        Dim invoiceNumber As Integer = 1
        Dim foundInvoice = invoiceList.Find(Function(invoice) invoice.InvoiceNumber = invoiceNumber)

更多示例,包括日期搜索,请参考Mike McIntyre的博客文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接