我想在我的ListBox中计数重复的项目。
例如。我的单子里有这个。
巧克力 芒果 甜瓜 巧克力 巧克力 草莓 巧克力 草莓
我想要的是这个输出。
巧克力-4
草莓-2
芒果-1
瓜-1
发布于 2015-02-01 17:51:05
这是我为你写的一个小函数。这可以在任何地方使用,您所需要做的就是将ListBox对象传递给它;它将返回一个包含项目及其计数的字符串。如果您计划需要这些值等等,您也可以更改它以返回Dictionary,如果您想要返回一个字符串。
''' <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))https://stackoverflow.com/questions/28264145
复制相似问题