Jonathan
Jonathan

Reputation: 2073

VB: ArrayList with string as index (key)

Is there a way to insert values into an arraylist and assign them with a string as key/index?

I tried:

arrayList.Insert("abc", "value123")

Upvotes: 0

Views: 2635

Answers (2)

M41DZ3N
M41DZ3N

Reputation: 346

What you want is a StringDictionary

http://msdn.microsoft.com/en-us/library/system.collections.specialized.stringdictionary.add(v=vs.110).aspx

  Dim myCol As New StringDictionary()
  myCol.Add("red", "rojo")

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460380

First, there is no need to use an ArrayList anymore. Use a typed List(Of T) to avoid that you always have to cast the objects which is also more error-prone.

In this case it seems that you actually need a Dictionary(Of String, String):

Dim dict As New Dictionary(Of String, String)
dict.Add("abc", "value123")

Now you can access it by key very fast:

Dim value As String = dict("abc") ' exception if it doesnt contain this key '

Note that the keys must be unique and that you can use TryGetValue or ContainsKey to check whether or not it contains the key to avoid the exception.

Upvotes: 4

Related Questions