How to update the value stored in Dictionary in C#?

C#Dictionary

C# Problem Overview


How to update value for a specific key in a dictionary Dictionary<string, int>?

C# Solutions


Solution 1 - C#

Just point to the dictionary at given key and assign a new value:

myDictionary[myKey] = myNewValue;

Solution 2 - C#

It's possible by accessing the key as index

for example:

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

Solution 3 - C#

You can follow this approach:

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;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary. If you use ContainsKey to check the existance and update the value using dic[key] = val + newValue; then you are accessing the dictionary twice.

Solution 4 - C#

Use LINQ: Access to dictionary for the key and change the value

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

Solution 5 - C#

Here is a way to update by an index much like foo[x] = 9 where x is a key and 9 is the value

var views = new Dictionary<string, bool>();

foreach (var g in grantMasks)
{
    string m = g.ToString();
    for (int i = 0; i <= m.Length; i++)
    {
        views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
    }
}

Solution 6 - C#

This simple check will do an upsert i.e update or create.

if(!dictionary.TryAdd(key, val))
{
    dictionary[key] = val;
}

Solution 7 - C#

  1. update - modify existent only. To avoid side effect of indexer use:

    int val;
    if (dic.TryGetValue(key, out val))
    {
        // key exist
        dic[key] = val;
    }
    
  2. update or (add new if value doesn't exist in dic)

    dic[key] = val; for instance:

    d["Two"] = 2; // adds to dictionary because "two" not already present d["Two"] = 22; // updates dictionary because "two" is now present

Solution 8 - C#

This may work for you:

Scenario 1: primitive types

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

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

Scenario 2: The approach I used for a 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...

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

Hope it's useful for someone in need of help.

Solution 9 - C#

This extension method allows a match predicate delegate as the dictionary key selector, and a separate delegate to perform the dictionary value replacement, so it's completely open as to the type of key/value pair being used:

public static void UpdateAll<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, Func<TKey, TValue, bool> matchPredicate, Func<TValue, TValue> updatePredicate)
{
  var keys = dictionary.Keys.Where(k => matchPredicate(k, dictionary[k])).ToList();
  foreach (var key in keys)
  {
    dictionary[key] = updatePredicate(dictionary[key]);
  }
}

Example usage:

	Dictionary<int, string> dict = new Dictionary<int, string>();
	dict.Add(1, "One");
	dict.Add(2, "Two");
	dict.Add(3, "Three");

	//Before
	foreach(var kvp in dict){
	  Console.WriteLine(kvp.Value);
	}

	dict.UpdateAll(
	    matchPredicate: (k, v) => k >= 2, //Update any dictionary value where the key is >= 2
        updatePredicate: (v) => v = v + " is greater than One"
      );

	//After
	foreach(var kvp in dict){
	  Console.WriteLine(kvp.Value);
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmitView Question on Stackoverflow
Solution 1 - C#ccalboniView Answer on Stackoverflow
Solution 2 - C#AmitView Answer on Stackoverflow
Solution 3 - C#max_forceView Answer on Stackoverflow
Solution 4 - C#INT_24hView Answer on Stackoverflow
Solution 5 - C#MatthewView Answer on Stackoverflow
Solution 6 - C#saad bin samiView Answer on Stackoverflow
Solution 7 - C#Vlad NovakovskyView Answer on Stackoverflow
Solution 8 - C#Mister PittView Answer on Stackoverflow
Solution 9 - C#BobTView Answer on Stackoverflow