Chrisetiquette
Chrisetiquette

Reputation: 321

Count of each unique value in a list

I need to find the unique values from a list and the number of times each value occurred in the original list. Here is what i have so far:

Dim Lister As New List(Of String)()

For Each item In eColumn
    Lister.Add(item.value)
Next

Dim Result As New List(Of String)
Result = Lister.Distinct().ToList

For Each st In Result
    MsgBox(st)
Next

The result is a list of all the unique values, but does not include a count for each item. For example, if my list was

John
John
Abbey
Larry
Larry
Larry
Charles

I want 4 values returned: John = 2, Abbey = 1,Larry = 3, Charles = 1.

Upvotes: 1

Views: 4421

Answers (1)

soohoonigan
soohoonigan

Reputation: 2350

Using linq's .Distinct() is only going to give you a list containing each distinct name in your list; so as you must have seen when your messagebox loop ran, it just shows you each name that is in your list once.

VB's lists do not have a native function for returning the count of an item's occurrences in a list, so to achieve your desired result just group them using linq's .GroupBy() function. It will return a Linq.GroupedEnumerable object, which can be iterated through and also possesses the kind of count property you're looking for:

    Dim myList As New List(Of String) From {"John", "John", "Abbey", "Larry", "Larry", "Larry", "Charles"}

    Dim groupedNames = myList.GroupBy(Function(x) x)
    If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then
        For Each person In groupedNames
            Debug.Print(person.Key & "-" & person.Count.ToString)
        Next
    End If

Output:

John-2
Abbey-1
Larry-3
Charles-1

Upvotes: 5

Related Questions