Home
VB.NET
Array.IndexOf, LastIndexOf
This page was last reviewed on Apr 21, 2023.
Dot Net Perls
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.
Shows an array
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.
If
Example. 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.
Then We call the Array.IndexOf Function. It returns the value 2, meaning it found the value 5 at index 2.
Finally We 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.
Shows an array
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
Negative 1. IndexOf and LastIndexOf return -1 if no matching element is found. When using these Functions, you must be careful to check for -1.
Info If you try to use -1 as an index to an array, you will receive an exception.
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.
String IndexOf
Summary. 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
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 21, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.