Array.IndexOf
The Array.IndexOf
function in VB.NET searches an array from its beginning. It returns the index of the element with the specified value.
LastIndexOf
, meanwhile, searches from the end of an array. Both functions return -1 if no match is found. We must test for -1 in an If
-Statement.
To start, we create an array of 6 elements. Please notice how the array has two elements with value 5—one is at index 2 and one is at index 5.
Array.IndexOf
Function. It returns the value 2, meaning it found the value 5 at index 2.LastIndexOf
. It returns the value 5, meaning it found the value 5 at index 5.IndexOf
and LastIndexOf
. They locate different elements in some arrays.Module Module1 Sub Main() Dim arr(5) As Integer arr(0) = 1 arr(1) = 3 arr(2) = 5 arr(3) = 7 arr(4) = 8 arr(5) = 5 ' Search array with IndexOf. Dim index1 As Integer = Array.IndexOf(arr, 5) Console.WriteLine(index1) ' Search with LastIndexOf. Dim index2 As Integer = Array.LastIndexOf(arr, 5) Console.WriteLine(index2) End Sub End Module2 5
IndexOf
and LastIndexOf
return -1 if no matching element is found. When using these Functions, you must be careful to check for -1.
Module Module1 Sub Main() ' An array. Dim arr() As Integer = {10, 20, 30} ' Search for a value that does not exist. Dim result As Integer = Array.IndexOf(arr, 100) Console.WriteLine(result) End Sub End Module-1
Usually when using IndexOf
functions in .NET, we must use If
-Statements and check for negative 1. If a value is guaranteed to be present, this step may not be needed.
These Functions are a declarative way to search an array for a specific matching value. When compared to a For
-Loop, this reduces code size.