Serhat Serhat - 3 months ago 10
Vb.net Question

String indexed arrays in VB .Net

I need an array indexed with strings, like this:

Dim Array ("A") as integer' <-- I need an array like this

Dim StringArray() as string = {"A","B","C","A","A","B","D"}

For each Letter in StringArray
Array(Letter) += 1
next


Results I wanted but not worked:

Array(A) = 3
Array(B) = 2
Array(C) = 1
Array(D) = 1


I, also tried List's, not working:

Dim Array As New List(Of Object)
Dim StringArray() as string = {"A","B","C","A","A","B","D"}

For each Letter in StringArray
Array(Letter) += 1
next


Is there a way count strings this way in VB .Net?

Answer

You can use a Dictionary(Of TKey, TValue) where your letters are the keys, and the values will store your totals:

Dim dict = New Dictionary(Of Char, Integer)
dict.Add("A"c, 0)
dict.Add("B"c, 0)
dict.Add("C"c, 0)
dict.Add("D"c, 0)

Dim stringArray() As Char = {"A"c, "B"c, "C"c, "A"c, "A"c, "B"c, "D"c}

For Each letter In stringArray
    dict.Item(letter) += 1
Next

enter image description here