How to count duplicate items in ListBox using Visual Basic 2008?

僤鯓⒐⒋嵵緔 提交于 2019-12-06 16:07:03

问题


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))


来源:https://stackoverflow.com/questions/28264145/how-to-count-duplicate-items-in-listbox-using-visual-basic-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!