Thursday, September 13, 2012

Dictionary- An item with the same key has already been added.

If you try to add same key to a Dictionary you may encounter this error

var ht = new Dictionary<String,String>();
ht.Add("key", "Data1");
.
.
.
ht.Add("key", "Data2");

To avoid this use you can simply change this code like

var ht = new Dictionary<String,String>();
ht["key"] = "Data1";
.
.
.
ht["key"] = "Data2";

This indexer will add the key, if it is not in the Dictionary, else will just update the value

No comments:

Post a Comment