tags:

views:

240

answers:

2

this question is related to this http://stackoverflow.com/questions/962558/multidimensional-associative-array-in-vb-net

getting the following error.

System.ArgumentException: An item with the same key has already been added. Line 103: AdInsured.Add(dbread.Item("FullName"), New Person(dbread.Item("FullName"), GetAge(dbread.Item("DateOfBirth"))))

Dim AdInsured As New Dictionary(Of String, Person)()

    Do While dbread.HasRows
        AdInsured.Add(dbread.Item("FullName"), New Person(dbread.Item("FullName"), GetAge(dbread.Item("DateOfBirth"))))
    Loop
+2  A: 

The key in a Dictionary must be unique. If you have an item with the key "John" and try to add one more with the same key you get this exception. You will need to make sure that each item in the dictionary is given a unique key. You can check whether a key is already used in the dictionary:

If AdInsured.ContainsKey(dbread.Item("FullName")) Then
    ' The dictionary already has an item with this key '
Else
    ' You can safely add the new item to the list '
    AdInsured.Add(dbread.Item("FullName"), New Person(dbread.Item("FullName"), GetAge(dbread.Item("DateOfBirth"))))
End If
Fredrik Mörk
A: 

When adding to a dictionary , the first item added would be the key (a string in this case ) - this must be unique within that dictionary otherwise this error will be thrown.

I would also use this declaration of the dictionary otherwise you could get an array of dictionaries

Dim adinsured as new Generic.Dictionary(Of String, Person)

i.e. if you added did this:

Dim adinsured2 as new Generic.Dictionary(Of String, String) Adinsured2.Add("Fred", "Fred") Adinsured2.Add("Fred", "Fred")

This would throw this error, however this would be fine

Dim adinsured2 as new Generic.Dictionary(Of String, String) Adinsured2.Add("Bert", "Fred") Adinsured2.Add("Fred", "Fred")