Search code examples
.netlistlinqtypesanonymous

Search Anonymous Type List with Linq


Is there a better way to find a value in an list of anonymous types? I would like to use linq.

Sub Main()
    Dim listOfAnonymousTypes = {
        New With {.Name = "John", .Age = 30},
        New With {.Name = "Alice", .Age = 25},
        New With {.Name = "Bob", .Age = 28}
    }

    Dim age = FindPersonsAge(listOfAnonymousTypes, "Bob")
End Sub
Function FindPersonsAge(list As Object, name As String) As Integer
    Dim result = Nothing
    For Each p In list
        If p.Name = name Then
            result = p.Age
            Exit For
        End If
    Next
    Return result
End Function

Solution

  • Yes

    Dim age = listOfAnonymousTypes.FirstOrdefault(Function(x) x.Name = "Bob")?.Age
    

    Note that the result is an Integer? because of the null conditional operator. So if there is no "Bob" the result is Nothing. You can use HasValue and Value to get the Integer-value.