In this article, we’ll be looking at ways to update a value stored in a dictionary. A dictionary is a class in C# that allows us to store a collection of key/value pairs in a strongly typed way.
Let’s start by creating a simple dictionary collection.
Creating a Dictionary in C#
We’ll create a ToppingsDictionary
class with one property called Toppings
:
Toppings = new Dictionary<string, int>() { { "pepperoni", 4 }, { "meatball", 8 }, { "olive", 0 } };
This property holds a collection of toppings as the key and the total number of that topping as a value. We initialize the collection with some toppings to start with.
Updating a Dictionary Value With the Indexer
The simplest way to update a dictionary value in C# is to use the indexer. So, let’s create a method that updates the dictionary value using this approach:
public void AddToppings(string toppingType, int amount) { Toppings[toppingType] = Toppings[toppingType] + amount; }
In this method, we use the toppingType
string in the Toppings
dictionary indexer to get the value for that key. Then we add the amount
passed into the method to the value we get back from the dictionary.
Let’s create a new instance of our ToppingsDictionary
class and call our AddToppings
method:
var toppingsDictionary = new ToppingsDictionary(); toppingsDictionary.AddToppings("pepperoni", 4); toppingsDictionary.AddToppings("olive", 3);
Now, let’s print each key and value from our dictionary to see how the values have been updated:
foreach (var topping in toppingsDictionary.Toppings) { Console.WriteLine($"{topping.Key} = {topping.Value}"); }
We can see that this is the output produced:
pepperoni = 8 meatball = 8 olive = 3
What Are the Risks of Updating a Dictionary Value With the Indexer?
The previous examples work without any problems because the keys that we use in the indexer already exist in the Toppings
dictionary. But, let’s use our AddToppings
method and pass in a topping type that doesn’t exist in our dictionary yet:
toppingsDictionary.AddToppings("jalepeno", 1);
We get the exception as a result:
System.Collections.Generic.KeyNotFoundException: The given key 'jalepeno' was not present in the dictionary.
How to Use ContainsKey to Ensure the Dictionary Key Exists
We can check if a key exists in a C# dictionary by using the dictionary’s ContainsKey
method. It accepts a key as a parameter and returns true
if the key exists in the dictionary and false
if the key doesn’t exist.
Let’s update our AddToppings
method to make use of the ContainsKey
method:
public void AddToppings(string toppingType, int amount) { if (Toppings.ContainsKey(toppingType)) { Toppings[toppingType] = Toppings[toppingType] + amount; } else { Toppings.Add(toppingType, amount); } }
Now, when we use our AddToppings
method with a key that doesn’t exist, the key and value will be added:
pepperoni = 8 meatball = 8 olive = 0 jalepeno = 1
Our AddToppings
method is working when we use it with a topping that doesn’t exist in our dictionary but it’s not very efficient. That’s because we’re accessing the dictionary twice when we update a value for a key that already exists. The first time is when we use the ContainsKey
method. The second time is when we get the existing value for the key using the indexer and add our new amount to it.
Fortunately, there’s a more concise way to check if a dictionary key exists and get the value in C#.
Use TryGetValue to Update the Value Stored in a Dictionary
The C# dictionary class has a method called TryGetValue
. It checks whether a key exists in the dictionary and outputs the value if it does.
Let’s update our AddTopping
method to replace our ContainsKey
usage with the TryGetValue
method:
public void AddToppings(string toppingType, int amount) { if (Toppings.TryGetValue(toppingType, out int currentAmount)) { Toppings[toppingType] = currentAmount + amount; } else { Toppings.Add(toppingType, amount); } }
Now, we’re checking that the topping already exists in the dictionary and when it does, we declare the value for it in a variable called currentAmount
. Then we use the currentAmount
variable to add the given amount to it, instead of retrieving the value again with the indexer.
Conclusion
In this article, we looked at a few different ways we can update the value stored in a dictionary. We started with the simplest implementation and then found out how to make it more reliable. Finally, we looked at how to make the code more efficient by using the TryGetValue
method.