IndexOf with String array in VB.NET

47,042

Solution 1

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)

MSDN page

Solution 2

Array.FindIndex(arr, (Function(c As String) c=strTokenKey)

Array.FindIndex(arr, (Function(c As String) c.StartsWith(strTokenKey)))

Solution 3

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")
Share:
47,042
Eugene
Author by

Eugene

Updated on May 18, 2020

Comments

  • Eugene
    Eugene about 4 years

    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.)

  • Eugene
    Eugene almost 14 years
    Assuming the array is populated (this was an example)... I get an error "Error 6 Overload resolution failed because no accessible 'IndexOf' accepts this number of arguments."
  • Oded
    Oded almost 14 years
    The overload selected will probably be Array.IndexOf<T>(T[], T), not the linked Array.IndexOf<T>(T[], Object).
  • Joel Mueller
    Joel Mueller almost 14 years
    You could do that, but finding the value of a string that exactly matches a hard-coded string would be pointless even if you didn't need the index rather than the value.
  • Hans Olsson
    Hans Olsson almost 14 years
    @Oded: Yep, got a bit confused. Thanks.
  • Chiramisu
    Chiramisu over 12 years
    Old post, but for anyone who finds it, be cautious when using this function as it will return only the index of the FIRST item encountered in the array with the passed value. So if your intent is to find a different item having the same value, this will not work for you. However, it works great if all values are guaranteed to be unique. :)