如何使用 Visual Basic 2008 计算 ListBox 中的重复项? [英] How to count duplicate items in ListBox using Visual Basic 2008?

查看:26
本文介绍了如何使用 Visual Basic 2008 计算 ListBox 中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算我的 ListBox 中的重复项.

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.

巧克力 - 4
草莓 - 2
芒果 - 1
甜瓜-1

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

推荐答案

这是我为你快速编写的一个小函数.这可以在任何地方使用,您只需将 ListBox 对象传递给它;它将返回一个包含项目及其计数的字符串.如果您打算需要这些值等,您也可以更改它以返回 Dictionary 而不是字符串.

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

如何使用示例我为此使用了 MessageBox...

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

这篇关于如何使用 Visual Basic 2008 计算 ListBox 中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆