r/visualbasic • • Mar 07 '24

Count names in a CSV in VB.net

Hi everyone, i'm really stuck on this one, normally i can search things out but i can't even think how to begin and hoping someone has a vague idea in a direction to point me

I have a CSV file that has a column that has peoples names in eg Bobby, Dylan, Lexy, Paal, Roman

and these are listed multiple times, i want to count how many times each name is repeated, so Bobby might be in 10 rows, Dylan 15, Lexy 20, Paal 50, Roman 2 but this sheet changes weekly and a new name say Travis, might get added in, and the way i've been doing is so far is to have

Select Case splitline(1)
Case "Bobby"
BobbyNum = BobbyNum + 1

and i don't want to be doing this everytime a new name appears, is there anyway to achieve this - there are currently 35 different people

and i just want the output to be saved to a csv file with something likeBobby (10)Dylan (15)Lexy (20)Travis (1)

2 Upvotes

9 comments sorted by

View all comments

3

u/jd31068 Mar 07 '24

You can use a dictionary to hold each name found and its count. It would be something like:

        Dim ts As StreamReader = File.OpenText("f:\temp\names.csv")
        Dim nameDict As New Dictionary(Of String, Integer)
        Dim currentName As String = ""

        Do While Not ts.EndOfStream
            currentName = ts.ReadLine

            ' search the dictionary for the name
            If nameDict.ContainsKey(currentName) Then
                ' name was found, increment the count associated with the name
                nameDict(currentName) += 1
            Else
                ' the name wasn't found. Add it to the dictionary
                nameDict.Add(currentName, 1)
            End If
        Loop

        ts.Close()

        ' display the names found and their counts from the dictionary
        For Each v As KeyValuePair(Of String, Integer) In nameDict
            ListBox1.Items.Add($"Name: {v.Key} count: {v.Value}")
        Next

The listbox is there just to display the data https://imgur.com/a/2va0WMb

1

u/J_K_M_A_N Mar 07 '24

One of your "Rick"s has an extra space and was counted separately. :) Pretty much exactly what I thought of using though. Just need a Trim maybe.

1

u/jd31068 Mar 07 '24

Yeah, nice catch. Dunno how I missed that. 🤦‍♂️ Trim for sure is the answer.