views:

76

answers:

3

How would I find the index of an item in the a string array 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.) Thanks!

+1  A: 

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")
Oded
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."
@user389823 - answer updated with correct code.
Oded
Ye that'll work. Thanks for the speedy responses=D
+1  A: 

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

ho1
That works! Thanks!
The overload selected will probably be `Array.IndexOf<T>(T[], T)`, not the linked `Array.IndexOf<T>(T[], Object)`.
Oded
@Oded: Yep, got a bit confused. Thanks.
ho1
A: 

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
epotter
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.
Joel Mueller