Search code examples
asp.netvb.netlist.net-2.0

Duplicates in List


I have this issue in VB.Net.

I have a List of type String.

Dim list As New List(Of String)

This list may or may not contain Duplicates.
Now what i want is, lets say the list has values {"10", "10", "10", "11", "11", "12"}
I want to create an Array(2-dimensional)/List which will give me value like this.
(3,10;(2,11);(1,12)

Simple means 10 exists 3 times, 11 exists 2 times and 12 exists 1 time.
Please don't dive me any LINQ replies as i am using VB.Net 2.0


Solution

  • In .NET 2, you'll have to track this yourself. The simplest way would likely be to build your own Dictionary(Of String, Integer) to store the counts, and loop manually:

    Dim dict = New Dictionary(Of String, Integer)
    For Each value in list
        If dict.ContainsKey(value) Then
             Dim count = dict(value)
             dict(value) = count + 1
        Else
             dict(value) = 1
        End If
    Next
    
    ' dict now contains item/count
    For Each kvp in dict
        Console.WriteLine("Item {0} has {1} elements", kvp.Key, kvp.Value)
    Next