Skip navigation.
Home

Use Predicate Functions with Lists

Use a predicate function to create a subset of a list. The new list will only contain items that match the function.

Sub Main()
    Dim lst As List(Of Integer) = getList()
    Dim evens As List(Of Integer) = lst.FindAll(New Predicate(Of Integer)(AddressOf GetEvens))
End Sub

The predicate function is a simple boolean function accepting items of the type in the list.

Private Function GetEvens(ByVal value As Integer) As Boolean
    Return value Mod 2 = 0
End Function

For simple predicates a Lambda function can be used.

Sub Main()
    Dim lst As List(Of Integer) = getList()
    Dim evens As List(Of Integer) = lst.FindAll(Function(value As Integer) value Mod 2 = 0)
End Sub

The same technique's can be used for all of the list Find methods (Find, FindAll, FindIndex, FindLast, FindLastIndex).