List, FindIn VB.NET the List Find Function receives a Predicate argument. This argument tests elements to see if they match. Find then returns the element that first matches your Predicate.
Meanwhile, Exists() is like Find but it returns true or false if an element exists. We replace loops with functions. We can use AddressOf or a lambda to call these functions.
Find exampleWe create a List of 3 Integers—this is the List we will search. We then invoke the Find function on this list with a lambda expression argument.
Find, we specify a lambda expression that returns True if the element is greater than 20.Find() method searches from the end of the list, not the start. It is like LastIndexOf.Module Module1
Sub Main()
Dim list As List(Of Integer) = New List(Of Integer)({19, 23, 29})
' Find value greater than 20.
Dim val As Integer = list.Find(Function(value As Integer)
Return value > 20
End Function)
Console.WriteLine(val)
End Sub
End Module23FindIndexThis function works the same way as Find except it returns the index of the match, not the match itself. You should assign an Integer Dim to its result.
FindIndex returns -1. We must test for this value if the element can possibly not exist.Module Module1
Sub Main()
Dim list As List(Of String) = New List(Of String)({"bird", "cat", "car"})
' Find index of first string starting with "c."
Dim index As Integer = List.FindIndex(Function(value As String)
Return value(0) = "c"c
End Function)
Console.WriteLine("FIRST C: {0}", index)
End Sub
End ModuleFIRST C: 1ExistsThis Function is just like Find—it accepts a Predicate argument. But it returns a True or False (Boolean) value instead of a List. If a matching element Exists, it returns True.
Module Module1
Sub Main()
Dim list As List(Of Integer) = New List(Of Integer)({20, -1, 3, 4})
' See if a negative number exists.
Dim result = list.Exists(Function(value As Integer)
Return value < 0
End Function)
Console.WriteLine("EXISTS: {0}", result)
' See if a huge number exists.
result = list.Exists(Function(value As Integer)
Return value >= 1000
End Function)
Console.WriteLine("EXISTS: {0}", result)
End Sub
End ModuleEXISTS: True
EXISTS: FalseThe List Find functions help us search List data. You can search from the beginning with Find and FindIndex, or from the end with FindLast and FindLastIndex.
Lambda expression syntax specifies the predicate function, which tests each element. Exists() and Find() are used with similar syntax. Exists() returns a Boolean, not a List.