Add or Update KeyValuePair in Dictionary


question:

What's the easiest way to add new key or update its value if it's already exists?

you can check if the key contains in the keys collection and then update the value of key and if the key doesn't exists you can add new item, but is it a best way ?

 

var tempDic = new Dictionary<string, string>();
                    
if (tempDic.ContainsKey("Key1"))
{
tempDic["key1"] = "value";
}
tempDic.Add("key1","value");



The best way is :


var tempDic = new Dictionary<string, string>();
tempDic["key1"] = "value";


you cannot use Add(TKey key, TValue value) method and you will get the following exception



Reference:
http://msdn.microsoft.com/en-us/library/k7z0zy8k.aspx

Comments