Serhat
Serhat

Reputation: 53

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?

Upvotes: 1

Views: 877

Answers (1)

rory.ap
rory.ap

Reputation: 35328

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

Upvotes: 4

Related Questions