Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update value of a key in dictionary in c#? [duplicate]

Tags:

I have the following code in c# , basically it's a simple dictionary with some keys and their values.

Dictionary<string, int> dictionary =     new Dictionary<string, int>(); dictionary.Add("cat", 2); dictionary.Add("dog", 1); dictionary.Add("llama", 0); dictionary.Add("iguana", -1); 

I want to update the key 'cat' with new value 5.
How could I do this?

like image 252
Ahsan Ashfaq Avatar asked Apr 12 '12 11:04

Ahsan Ashfaq


People also ask

Can you modify the value in a dictionary?

Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.

Can we update key in dictionary c#?

You need to remove the items and re-add them with their new key. Per MSDN: Keys must be immutable as long as they are used as keys in the SortedDictionary(TKey, TValue) .

How do you check if a key is in a dictionary C#?

Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.


2 Answers

Have you tried just

dictionary["cat"] = 5; 

:)

Update

dictionary["cat"] = 5+2; dictionary["cat"] = dictionary["cat"]+2; dictionary["cat"] += 2; 

Beware of non-existing keys :)

like image 118
J0HN Avatar answered Sep 23 '22 15:09

J0HN


Try this simple function to add an dictionary item if it does not exist or update when it exists:

    public void AddOrUpdateDictionaryEntry(string key, int value)     {         if (dict.ContainsKey(key))         {             dict[key] = value;         }         else         {             dict.Add(key, value);         }     } 

This is the same as dict[key] = value.

like image 33
cubski Avatar answered Sep 24 '22 15:09

cubski