0

Is it possible for a dictionary to have the same key more than once? I've looked around quite a bit and the answer seems to be YesNo. I'm reading in cc numbers from a csv file and adding them to a dictionary. Most posts that say no generally indicate that adding a key more than once throws an exception. This would have to be wrong because I haven't encountered this problem.
Basically I have this dictionary

Dim allCalls As New Dictionary(Of String, Array)

and I'm populating it like this

 Dim Path As String = My.Application.Info.DirectoryPath & "\Calls.txt"
    Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(Path)
    Dim parts() As String
    Dim lines() As String = IO.File.ReadAllLines(Path)

    Array.Sort(lines)
    For x As Integer = 0 To lines.GetUpperBound(0)
        parts = lines(x).Split(CChar(","))
        Dim data(1) As String
        data(0) = parts(2)
        data(1) = parts(5)
        allCalls.Add(parts(1), data)
    Next

    reader.Close()

This part is working just fine, but as far as if I'm overwriting my old data when I add the same key I couldn't tell you. However it seems counterintuitive to me that it wouldn't cause some sort of problem. Basically my goal is to be able to search this thing for a key and get all the array data back which I can't figure out how to do. I don't even really know if it is still in there so any help with how to work with these things would be great.

4

2 回答 2

0

我最终最终使用了一个 ArrayList 字典并将数组添加到其中。您绝对不能多次存储在同一个键上,但是检查它是否存在并添加到 arraylist 效果很好

于 2013-10-24T00:42:53.513 回答
0

如果您至少使用 .NET 3.5,则可以使用Lookup该类。

ALookup<TKey, TElement>类似于Dictionary<TKey, TValue>. 不同之处在于 aDictionary<TKey, TValue>将键映射到单个值,而 aLookup<TKey, TElement>将键映射到值的集合。

笔记

没有公共构造函数来创建 a 的新实例Lookup<TKey, TElement>。此外,Lookup<TKey, TElement>对象是不可变的,也就是说,您不能在Lookup<TKey, TElement>对象创建后添加或删除元素或键。

但你可以使用Enumerable.ToLookup

Dim allCalls As ILookup(Of String, String()) =
    (From line In IO.File.ReadAllLines(Path)
     Order By line
     Let tokens = line.Split(","c)
     Where tokens.Length >= 6).
ToLookup(Function(p) p.tokens(1), Function(p) {p.tokens(2), p.tokens(5)})

一个键可以返回零个、一个或多个值:

Dim calls = allCalls("Key")
For Each c As String In calls
    ' ... '
Next

请注意,如果密钥不存在,则不会出现异常。序列将是空的。

于 2013-10-20T19:29:59.447 回答