IndexOf with String array in VB.NET

本秂侑毒 提交于 2019-12-23 07:28:49

问题


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:


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




回答2:


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

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



回答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")



回答4:


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


来源:https://stackoverflow.com/questions/3670244/indexof-with-string-array-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!