VB.NET List Find Function: FindIndex, FindLast

Find icon

How can you use the Find function on the List type in your VB.NET programs? The Find function allows you to specify a predicate function that tells the condition that must be matched.

Examples

First, this program creates 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. This means that we locate the first String of length five characters.

This VB example program shows how to use the Find Function on the List type.

Program that uses Find, FindIndex, FindLast [VB.NET]

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
Note

Next part. 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").

Third example. Next we move on to the FindIndex function. This function works exactly the same way as Find except it returns the index of the match instead of the match itself. You should assign an Integer Dim to its result. If no match is found, it returns the value -1.

Final call. Finally, we use the FindLast function. This works exactly the same way as Find except is searches starting from the final element instead of the first element. You can see that it uses the same lambda expression as Find in the above example, but returns a different value.

Lambda Expression

Summary

The VB.NET programming language

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. The lambda expression syntax in VB.NET is used to formulate the predicate function, which tests each element.

List Tips VB.NET Tutorials
.NET