Array Count

zekeman

Well-known member
Joined
May 23, 2006
Messages
224
Programming Experience
10+
If you had many sheets of paper in front of you and each sheet contained a list of parts and one part could be found in multiple places, how could I get a count of all the parts.

I.E.

with array:
array('orange','banana','orange')

I want to get:

orange: 2
banana: 1
 
Perhaps using a Dictionary?
VB.NET:
'data
Dim arr() As String = {"orange", "banana", "orange"}
 
'analyze
Dim dc As New Dictionary(Of String, Integer)
For Each item As String In arr
    If dc.ContainsKey(item) Then
        dc(item) += 1
    Else
        dc.Add(item, 1)
    End If
Next
 
'present
Dim sb As New System.Text.StringBuilder
For Each key As String In dc.Keys
    sb.AppendFormat("{0}: {1}", key, dc(key).ToString)
    sb.AppendLine()
Next
MsgBox(sb.ToString)
 
Back
Top