简体   繁体   中英

asp.net vb.net person class and dictionary

this question is related to this 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

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

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)

ie 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM