Question

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

Était-ce utile?

La 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

Autres conseils

Why not use a dictionary:

    Dim lookup As New Dictionary(Of String, Integer)
    For Each sz As String In list
        If Not lookup.ContainsKey(sz) Then lookup.Add(sz, 0)
        lookup(sz) += 1
    Next

You need to use a Dictionary(Of String, Integer) to hold the counts of each unique value, like this:

Dim dict As New Dictionary(Of String, Integer)

For Each item As String In list
    If dict.ContainsKey(item) Then
        dict(item) += 1
    Else
        dict.Add(item, 1)
    End If
Next

Now you can loop through the dictionary and use the results, like this:

For Each result As String In dict.Keys
    ' Do something with result
Next
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top