IndexOf with String array in VB.NET
Question
How would I find the index of an item in the string array in the following code:
Dim arrayofitems() as String
Dim itemindex as UInteger
itemindex = arrayofitems.IndexOf("item test")
Dim itemname as String = arrayofitems(itemindex)
I'd like to know how I would find the index of an item in a string array. (All of the items are lowercase, so case shouldn't matter.)
Solution
It's a static (Shared
) method on the Array
class that accepts the actual array as the first parameter, as:
Dim arrayofitems() As String
Dim itemindex As Int32 = Array.IndexOf(arrayofitems, "item test")
Dim itemname As String = arrayofitems(itemindex)
OTHER TIPS
Array.FindIndex(arr, (Function(c As String) c=strTokenKey)
Array.FindIndex(arr, (Function(c As String) c.StartsWith(strTokenKey)))
IndexOf
will return the index in the array of the item passed in, as appears in the third line of your example. It is a static (shared) method on the Array
class, with several overloads - so you need to select the correct one.
If the array is populated and has the string "item test" as one of its items then the following line will return the index:
itemindex = Array.IndexOf(arrayofitems, "item test")
For kicks, you could use LINQ.
Dim items = From s In arrayofitems _
Where s = "two" _
Select s Take 1
You would then access the item like this:
items.First