VB.NET Array.IndexOf, LastIndexOfInvoke the Array.IndexOf and LastIndexOf Functions to search for elements by value.
dot net perls

Array.IndexOf. Array.IndexOf searches an array from its beginning. It returns the index of the element with the specified value. LastIndexOf, meanwhile, searches from the end. Both methods return -1 if no match is found.


Example. To start, we create an array of six elements. We use the maximum index of the array in its declaration. Please notice how the array has two elements with value 5—one is at index 2 and one is at index 5.

IndexOf We then call the Array.IndexOf Function. It returns the value 2, meaning it found the value 5 at index 2.

LastIndexOf We finally call LastIndexOf. It returns the value 5, meaning it found the value 5 at index 5.

Here We see the difference between IndexOf and LastIndexOf. They locate different elements in some arrays.

VB.NET program that uses Array.IndexOf, LastIndexOf
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 Module
2 5

No match. IndexOf and LastIndexOf return -1 if no matching element is found. When using these Functions, you must be careful to check for -1. If you try to use -1 as an index to an array, you will receive an exception.

VB.NET program that uses IndexOf, finds no match
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

Summary. We observed the Array.IndexOf and LastIndexOf Functions. 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.

For Each, For

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.