IndexOf with String array in VB.NET
Asked Answered
R

4

10

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

Repent answered 8/9, 2010 at 17:15 Comment(1)
Isn't that what you're doing in the sample? arrayOfItems.IndexOf(string)Kimikokimitri
S
22

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

Shuster answered 8/9, 2010 at 17:21 Comment(3)
The overload selected will probably be Array.IndexOf<T>(T[], T), not the linked Array.IndexOf<T>(T[], Object).Cristal
@Oded: Yep, got a bit confused. Thanks.Shuster
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. :)Flatboat
C
2

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")
Cristal answered 8/9, 2010 at 17:19 Comment(1)
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."Repent
L
2
Array.FindIndex(arr, (Function(c As String) c=strTokenKey)

Array.FindIndex(arr, (Function(c As String) c.StartsWith(strTokenKey)))
Laurencelaurene answered 17/5, 2013 at 15:7 Comment(0)
3
-1

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
3d answered 8/9, 2010 at 17:36 Comment(1)
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.Stoecker

© 2022 - 2024 — McMap. All rights reserved.