VB.Net List.Find. Pass values to predicate

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.


I have an object that manages a list of Unique Property Types. Example:

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

Here is some code to check if properties already exist

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

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.

Tags:

Vb.Net