2016-03-14 50 views
1

我想使用字典來存儲一個鍵的多個字符串。例如,密鑰將是「披頭士」,而字符串數組將包含我擁有的所有「記錄」。下一個關鍵將是「滾石」,這將保存我爲這個樂隊所擁有的所有唱片等。字符串數組作爲值導致重複的鍵錯誤

當我從文本文件中查看我擁有的記錄列表時,我想更新該詞典,並添加更多的記錄到陣列。

這可能嗎?我不斷收到「具有相同密鑰的項目已被添加」錯誤消息。

Dim Records_I_Own As New Dictionary(Of String, String()) 

For each Line in Lines_I_Read 

    .... 
    .... 
    Records_I_Own.Add(Band, Record) 
    .... 
    .... 

Loop 
+0

錯誤表示「Band」變量具有相同的值兩次或更多次。你應該確保它不是 –

回答

2

您每次閱讀某一行時都會添加一個樂隊並進行錄製。當你遇到一個你已經添加的樂隊時,你會得到這個錯誤,因爲一個字典的全部重點是沒有重複的鍵。

你需要做的是將記錄添加到樂隊的字符串數組。

你需要檢查,看看是否已經有樂隊(key

所以,你需要做這樣的事情:

For each Line in Lines_I_Read 

    .... 
    .... 
    If Records_I_Own.ContainsKey(Band) Then 
     'We already have this artist so add a new record to the value collection 
     'get the array 
     Dim records as String() = Records_I_Own(Band) 
     'extend the array 
     ReDim Preserve records(records.Count) 
     'add the new record on the end 
     records(records.Count - 1) = record 
     'copy the array back to the dicationary value 
     Records_I_Own(Band) = records 
    Else  
     'Add it as a new key and value 
     Records_I_Own.Add(Band, Record) 
    Endif 

    .... 
    .... 

Loop 

注意,它會更容易,如果你這樣做使用List(of String)而不是字符串數組,因爲您只需撥打.Add而不必擴展數組

+0

Records_I_Own.ContainsKey(Band)不會返回一個String()...它會返回一個布爾值,指示該密鑰是否已經存在於字典中... –

+0

@Martin - well spotted - copy一個錯字。現在修復 –

2

使用

Dictionary(of String, List(of String)) 

代替陣列。所以您可以添加

... 
if Not Records_I_Own.containsKey(Band) then 
    Records_I_own.Add(Band, New List(of String)) 
End If 
Records_I_Own(Band).Add(Record) 
.... 
相關問題