首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Visual 2008在ListBox中计数重复项?

如何使用Visual 2008在ListBox中计数重复项?
EN

Stack Overflow用户
提问于 2015-02-01 15:06:47
回答 1查看 2K关注 0票数 0

我想在我的ListBox中计数重复的项目。

例如。我的单子里有这个。

巧克力 芒果 甜瓜 巧克力 巧克力 草莓 巧克力 草莓

我想要的是这个输出。

巧克力-4

草莓-2

芒果-1

瓜-1

EN

回答 1

Stack Overflow用户

发布于 2015-02-01 17:51:05

这是我为你写的一个小函数。这可以在任何地方使用,您所需要做的就是将ListBox对象传递给它;它将返回一个包含项目及其计数的字符串。如果您计划需要这些值等等,您也可以更改它以返回Dictionary,如果您想要返回一个字符串。

代码语言:javascript
复制
''' <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 .

代码语言:javascript
复制
 MessageBox.Show(ReturnDuplicateListBoxItems(YOUR LISTBOX NAME HERE))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28264145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档