tags:

views:

279

answers:

2

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

here's the function for the predicate

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

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)

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?

+3  A: 

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

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.

Hans Passant
+2  A: 

I haven't needed to try this in newer versions of VB.Net which might have a nicer way, but in older versions the only way that I know of would be to have a shared member in your class to set with the value before the call.
There's various samples on the net of people creating small utility classes to wrap this up to make it a little nicer.

ho1