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. It replaces iterative loops with a single Function call.
First, we create a List collection of five String instances—this is the List we will search. In the first call to Find, we specify a lambda expression (with Function() syntax) that returns True if the parameter String has length of five.ListStrings
Note:This means that we locate the first String of length five characters in the List.
VB.NET program that uses Find, FindIndex, FindLast Module Module1 Sub Main() Dim list As List(Of String) = New List(Of String) list.Add("dot") list.Add("net") list.Add("perls") list.Add("Thank") list.Add("You") ' Find first five-letter string. Dim val As String = list.Find(Function(value As String) Return value.Length = 5 End Function) Console.WriteLine(val) ' Find first uppercased string. val = list.Find(Function(value As String) Return Char.IsUpper(value(0)) End Function) Console.WriteLine(val) ' Find index of first string starting with n. Dim index As Integer = list.FindIndex(Function(value As String) Return value(0) = "n"c End Function) Console.WriteLine(index) ' Find last five-letter string. val = list.FindLast(Function(value As String) Return value.Length = 5 End Function) Console.WriteLine(val) End Sub End Module Output perls Thank 1 Thank
The second call to Find in the above program also uses a lambda expression. This lambda returns True if the first character of the String is uppercase. We therefore locate the first uppercased String in the List ("Thank").
Next we move on to the FindIndex function. This 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. If no match is found, it returns -1.
Finally:We use the FindLast function. This works the same way as Find except it searches starting from the final element.
Tip:You can see that it uses the same lambda expression as Find in the above example, but returns a different value.Lambda Expressions
The Find functions on the List type in the VB.NET language provide a powerful and declarative mechanism for searching List data. You can search from the beginning with Find and FindIndex, or from the end with FindLast and FindLastIndex.
Review:The lambda expression syntax in VB.NET is used to formulate the predicate function, which tests each element.