How to count duplicate items in ListBox using Visu

2019-04-17 13:23发布

问题:

I want to count duplicate items in my ListBox.

Ex. I have this in my List Box.

Chocolate
Mango
Melon
Chocolate
Chocolate
Strawberry
Chocolate
Strawberry

What I want is to have this output.

Chocolate - 4
Strawberry - 2
Mango - 1
Melon -1

回答1:

Here's a little function I wrote real quick for you. This can be used anywhere and all you need to do is pass the ListBox object to it; it will return a string containing the item's and their count's. You can change this as well to return the Dictionary if you want instead of a string if you plan on needing the values and such.

''' <summary>
''' Return's a string containing each item and their count
''' </summary>
''' <param name="lBox"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function ReturnDuplicateListBoxItems(ByVal lBox As System.Windows.Forms.ListBox) As String
    Dim strReturn As New System.Text.StringBuilder
    Dim lItems As New Dictionary(Of String, Integer)
    Dim intCount As Integer = 0
    Dim strCurrentItem As String = String.Empty

    Try
        'Loop through listbox grabbing items...
        For Each nItem As String In lBox.Items
            If Not (lItems.ContainsKey(nItem)) Then 'Add listbox item to dictionary if not in there...
                'The current item we are looking at...
                strCurrentItem = nItem
                'Check how many occurances of this items there are in the referenced listbox...
                For Each sItem As String In lBox.Items
                    If sItem.Equals(strCurrentItem) Then 'We have a match add to the count...
                        intCount += 1
                    End If
                Next
                'Finally add the item to the dictionary with the items count...
                lItems.Add(nItem, intCount)

                'Reset intCount for next item... and strCurrentItem
                intCount = 0
                strCurrentItem = String.Empty
            End If
        Next

        'Add to the string builder...
        For i As Integer = 0 To lItems.Count - 1
            strReturn.AppendLine(lItems.Keys(i).ToString & " - " & lItems.Values(i).ToString)
        Next

    Catch ex As Exception
        Return strReturn.ToString
    End Try

    Return strReturn.ToString
End Function

How to Use Example I used a MessageBox for this...

 MessageBox.Show(ReturnDuplicateListBoxItems(YOUR LISTBOX NAME HERE))