Problem
Dictionaries require keys to be unique. When you try to add a key/value to a dictionary and the key already exists, you get the following exception:
System.ArgumentException: An item with the same key has already been added.
This can happen when you use Dictionary.Add() or when you initialize a dictionary using the “curly brace” syntax. The following two code snippets show an example that results in this ArgumentException:
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>();
dictionary.Add("Bob", 1);
dictionary.Add("Bob", 2); //duplicate key => exception
Code language: C# (cs)
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>()
{
{ "Bob", 1 },
{ "Bob", 2 } //duplicate key => exception
};
Code language: C# (cs)
If you accidently initialized the dictionary with duplicate keys, go ahead and remove the duplicates in the initializer. Otherwise, I’ll explain three options for solving this below.
Option 1 – Use Dictionary.TryAdd()
The simplest solution is to use Dictionary.TryAdd() to add the key/value to the dictionary. This adds the key if it doesn’t exist, otherwise it does nothing (instead of throwing an exception).
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>();
dictionary.TryAdd("Bob", 1);
dictionary.TryAdd("Bob", 2); //does nothing
Console.WriteLine($"Value={dictionary["Bob"]}"); //outputs "Value=1"
Code language: C# (cs)
Note: TryAdd() returns true if it was able to add the key. Check that return value if you want.
TryAdd() is a shortcut for checking if the key exists with Dictionary.ContainsKey() and then adding with Dictionary.Add().
Option 2 – Insert or update key
Another option is to add the key/value using the indexer syntax (i.e. dictionary[key] = value). This inserts the key/value or updates the existing key’s value in the dictionary (instead of throwing an exception). Here’s an example:
using System.Collections.Generic;
var dictionary = new Dictionary<string, int>();
dictionary["Bob"] = 1;
dictionary["Bob"] = 2;
Console.WriteLine($"Value={dictionary["Bob"]}"); //outputs "Value=2"
Code language: C# (cs)
This is a nice approach when you simply want the key to have the latest value and don’t want to explicitly check if the key exists every time.
Option 3 – Use a dictionary of lists if you need multiple values per key
Keys are mapped to exactly one value. When you want a key to have multiple values, you can use a dictionary of lists:
- Create the dictionary with a value of type List<T>.
- If the key doesn’t exist, add it with a new list.
- Add the value to the list.
Here’s an example of how to do this:
using System.Collections.Generic;
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("Bob"))
dictionary["Bob"] = new List<int>();
dictionary["Bob"].Add(1);
dictionary["Bob"].Add(2);
Code language: C# (cs)
Note: You can use TryGetValue(), but I find ContainsKey() to be easier to understand at a glance.