2

我在 VB.Net 中有这个问题。

我有一个字符串类型的列表。

Dim list As New List(Of String)

此列表可能包含也可能不包含重复项。
现在我想要的是,假设列表具有值 {“10”、“10”、“10”、“11”、“11”、“12”}
我想创建一个数组(二维)/列表这会给我这样的价值。
(3,10;(2,11);(1,12)

简单意味着 10 存在 3 次,11 存在 2 次,12 存在 1 次。
请不要LINQ在我使用时给我任何回复VB.Net 2.0

4

3 回答 3

3

在 .NET 2 中,您必须自己跟踪。最简单的方法可能是自己构建Dictionary(Of String, Integer)来存储计数,然后手动循环:

Dim dict = New Dictionary(Of String, Integer)
For Each value in list
    If dict.ContainsKey(value) Then
         Dim count = dict(value)
         dict(value) = count + 1
    Else
         dict(value) = 1
    End If
Next

' dict now contains item/count
For Each kvp in dict
    Console.WriteLine("Item {0} has {1} elements", kvp.Key, kvp.Value)
Next
于 2013-08-05T17:36:09.987 回答
2

为什么不使用字典:

    Dim lookup As New Dictionary(Of String, Integer)
    For Each sz As String In list
        If Not lookup.ContainsKey(sz) Then lookup.Add(sz, 0)
        lookup(sz) += 1
    Next
于 2013-08-05T17:36:00.077 回答
1

您需要使用 aDictionary(Of String, Integer)来保存每个唯一值的计数,如下所示:

Dim dict As New Dictionary(Of String, Integer)

For Each item As String In list
    If dict.ContainsKey(item) Then
        dict(item) += 1
    Else
        dict.Add(item, 1)
    End If
Next

现在您可以遍历字典并使用结果,如下所示:

For Each result As String In dict.Keys
    ' Do something with result
Next
于 2013-08-05T17:37:32.897 回答