列表中的重复项

时间:2013-08-05 17:28:44

标签: asp.net vb.net list .net-2.0

我在VB.Net中遇到过这个问题。

我有一个String类型的列表。

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个回复

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:1)

您需要使用Dictionary(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