How do I update the values stored in Dictionary in C?

How to update the value dictionary < string, int > of a specific key in the dictionary?

#1 building

Just specify the dictionary for the given key and a new value:

myDictionary[myKey] = myNewValue;

#2 building

Can be indexed by access key

For example:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2

#3 building

You can follow these methods:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
    int val;
    if (dic.TryGetValue(key, out val))
        // yay, value exists!
        dic[key] = val + newValue;
        // darn, lets add the value
        dic.Add(key, newValue);

The advantage you get here is that you only need to visit the dictionary once to check and get the value of the corresponding key. If you use ContainsKey to check the existence and use dic[key] = val + newValue; update value dic[key] = val + newValue; then you access the dictionary twice.

#4 building

Using LINQ: access the dictionary of the key and change the value

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

#5 building

This may work for you:

Scenario 1: original type

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};

   dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
   dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

Scenario 2: my method for List as Value

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...

   dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
   dictToUpdate[keyToMatch] = objInValueListToAdd;

I hope it's useful for people in need.

Posted on Sun, 09 Feb 2020 06:38:03 -0800 by ghostdog74