C# Add to a Dictionary
By FoxLearn 1/21/2025 7:45:11 AM 21
using System.Collections.Generic; var dictionary = new Dictionary<string, int>(); dictionary.Add("Alice", 5);
If the key already exists, Dictionary.Add() will throw an ArgumentException, as each key must be unique.
Add or update key/value in dictionary
You can use the dictionary indexer syntax to add a new key/value pair or overwrite the value if the key already exists (instead of throwing an exception).
using System.Collections.Generic; var dictionary = new Dictionary<string, int>(); dictionary["Alice"] = 5; dictionary["Alice"] = 20;
This provides a simple way to add or overwrite a value without explicitly checking if the key exists.
Initialize key/value or increment the value
Let’s say you want to initialize a key’s value to 10 and increment it by 1 if the key already exists. To do this, you must explicitly check if the key exists and set the initial value. You can use Dictionary.TryGetValue()
to get the current value. If this returns true
, you can update the value. If it returns false
, you can set the initial value.
using System.Collections.Generic; var dictionary = new Dictionary<string, int>(); string key = "Alice"; if (dictionary.TryGetValue(key, out int currentValue)) { dictionary[key] = currentValue + 1; } else { dictionary[key] = 10; // set initial value }
You need to check if the key exists first, because using just the indexer syntax (e.g., dictionary[key]++
) will result in a KeyNotFoundException
. This is because the key has to be looked up to increment its value, but if it doesn’t exist, the exception will occur.
Add to the dictionary if the key doesn’t exist
You can use Dictionary.TryAdd()
to attempt adding a key/value pair to the dictionary. If the key already exists, it returns false
instead of throwing an exception.
using System.Collections.Generic; var dictionary = new Dictionary<string, int>(); dictionary.TryAdd("Alice", 10); dictionary.TryAdd("Alice", 20); Console.WriteLine($"Alice={dictionary["Alice"]}");
This will output the following (notice that it didn’t overwrite the value and didn’t throw an exception):
Alice=10
This is a shortcut for using Dictionary.ContainsKey()
and Dictionary.Add()
.
If necessary, you can check the output of TryAdd()
. It returns true
if the key/value pair was successfully added.
using System.Collections.Generic; var dictionary = new Dictionary<string, int>(); if (dictionary.TryAdd("Alice", 10)) { Console.WriteLine("Added key/value pair!"); }
Adding multiple items when creating the dictionary
Another way to add key/value pairs to a dictionary is by using the collection initializer syntax. This allows you to add items while creating the dictionary. It’s equivalent to using the indexer syntax repeatedly but more concise.
using System.Collections.Generic; var dictionary = new Dictionary<string, int>() { ["Alice"] = 10, ["Bob"] = 20, ["Charlie"] = 30 };
If you have a list of items to add, you can convert the list to a dictionary with ToDictionary()
.