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

时间:2010-04-16 20:04:26

标签: vb.net

使用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 个答案:

答案 0 :(得分:22)

您可以使用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”设为您班级的私有字段。检查this thread中的代码以获得更清晰的解决方案。

答案 1 :(得分: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 :(得分:2)

我不需要在较新版本的VB.Net中尝试这一点,这可能有更好的方法,但在旧版本中,我所知道的唯一方法是让你的类中有一个共享成员来设置通话前的价值 网上有各种各样的样本创建小实用程序类来包装它以使它更好一些。

答案 3 :(得分: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的博客Post