Categories
Software Development Technology

The Simple Solution to List.Find()

Today at work, it was necessary to code a solution that included a List.Find() that I've coded many times and has become almost second nature . . . in C#. However, the app, being written in VB, required a solution in VB. After some searching on the web, I was left without a satisfactory solution. After several (read: many) rounds of trial and error, I finally stumbled upon the correct syntax. Later this afternoon it occurred to me that this would make an excellent inaugural blog post.

In C#, the code is very simple (examples can be found on MSDN). Assuming we have an object named Person that has a property named FirstName of type string:

string strPersonToFind = "Justin";
Person myPerson = People.Find(
    delegate (Person p)
    {
        return p.FirstName == strPersonToFind;
    });

In VB, the examples were far less clean:

Dim strPersonToFind As string = "Justin"
Sub doSomething(ByVal People As List(Of Person))
    Person myPerson = People.Find(addressof FindPerson)
End Sub
Function FindPerson(ByVal s As string) As Boolean
    If s = strPersonToFind Then
        Return True
    Else
        Return False
    End If
End Function

Seriously? The VB example has several obvious shortcomings. First, it requires a page-scoped variable for comparison or a hard-coded comparator. Second, it took 11 lines of code to accomplish what was done in C# in 3. Third, it's just plain ugly; it requires jumping between Subs & Functions and is pretty hard to follow and maintain.

The solution is very simple, looks similar to the C# example, and can be used from within a single Sub or Function (eliminating the need for page-scoped variables):

Dim strPersonToFind As string = "Justin"
Person myPerson = People.Find(Function(ByVal p As Person) p.FirstName = strPersonToFind)

Only two lines of code and very clear and concise syntax.

Important Notes: This is in reference to System.Collections.Generic.List<T> (C#) and System.Collections.Generic.List(Of T) (VB). Also, I believe this known as Lambda Expression syntax and as such, only works .NET 3.5 and higher.

If this helped you, let me know in the comments!

Categories
Meta

Welcome to JustKarp

After much prodding, I have finally launched my own blog. Stay tuned for information regarding software development, technology, spirituality, and life in general. Stay tuned for my thoughts regarding software development, web design & development, spirituality, and life!