1

I'd like to use a Dictionary to store multiple strings for a key.

For instance, the Key will be "The Beatles", and the array of Strings Will contain all "Records" I own. The next key will be "Rolling Stones" and this will hold all the records I own for this band, etc.

As I go through a list of records I own, from a text file, I'd like to update the Dictionary, and add more Records to the Array.

Is this possible? I keep getting "An item with the same key has already been added" error messages.

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

 For each Line in Lines_I_Read

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

 Loop
1
  • The error means that the Band variable has the same value two or more times. You should make sure it isn't Commented Mar 14, 2016 at 9:43

2 Answers 2

2

You add a Band and record every time you read a line. When you get to a band that you have already added you will get this error because the whole point of a dictionary is that there are not duplicate keys.

What you need to do is add the record to the string array of the band.

You need to check to see if you already have the Band (key)

So you need to do something like this:

 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

Note that it would be easier to do this if you used a List(of String) instead of a String Array because you can just call.Add instead of having to extend the array

Sign up to request clarification or add additional context in comments.

2 Comments

Records_I_Own.ContainsKey(Band) does not return a String()... It does return a boolean indicating if the key already exists in the Dictionary...
@Martin - well spotted - copy an paste typo. Now fixed
2

Use a

Dictionary(of String, List(of String))

instead of an array. So you can add

...
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)
....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.