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

1
  • Isn't that what you're doing in the sample? arrayOfItems.IndexOf(string) Commented Sep 8, 2010 at 17:17

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

3 Comments

The overload selected will probably be Array.IndexOf<T>(T[], T), not the linked Array.IndexOf<T>(T[], Object).
@Oded: Yep, got a bit confused. Thanks.
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. :)
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")

1 Comment

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."
2
Array.FindIndex(arr, (Function(c As String) c=strTokenKey)

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

Comments

-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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.