C# – Copy a dictionary

The simplest way to make a copy of a dictionary is to use the copy constructor. You pass the dictionary you want to copy to the new dictionary’s constructor, like this: Note: If you’re using a non-default comparer, you’ll want to pass it to the copy constructor (i.e. new Dictionary(d, d.Comparer)). The copy constructor handles … Read more

C# – Find duplicate values in a dictionary

Dictionaries contain key/value pairs. The keys must be unique, but the values can be repeated many times. When you want to find duplicate values, the simplest option is to use Linq methods GroupBy() and Where(), like this: Note: I initialized the dictionary with a few duplicate values. This groups the dictionary key/value pairs by value. … Read more

C# – Get dictionary key by value

Dictionaries have keys mapped to values, which enables you to efficiently lookup values by key. But you can also do a reverse lookup: get the key associated with a value. The simplest option is to use FirstOrDefault(), but that’s only a good idea if you know the value exists for sure. Instead, the best option … Read more

C# – Check if a value exists in dictionary

Normally you’d check if a dictionary contains a key or get a value by key. But you can also check if the dictionary contains a specific value by using Dictionary.ContainsValue(). Here’s an example: Dictionary.ContainsValue() returns true if the value was found and otherwise returns false. In this example, I initialized the dictionary with a single … Read more

C# – Check if key exists in dictionary

When you want to check if a key exists, use Dictionary.ContainsKey(). This returns true if the key exists and otherwise returns false. Here’s an example: This initializes the dictionary with a few items and then checks if one of the key exists. This outputs: Usually you’ll want to do something based on if the key … Read more

System.ArgumentException: An item with the same key has already been added

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” … Read more

C# – Remove items from dictionary

Dictionaries contain key/value pairs. When you want to remove one or more items from a dictionary, you can use one of the following methods: I’ll show examples below. Remove item by key Use Dictionary.Remove() to remove an item based on its key. If the key exists, it removes the key/value pair from the dictionary and … Read more

C# – Get value from dictionary

Dictionaries store key/value pairs. When you want to get the value for a key, you can use the indexer syntax and specify the key, like this: Note: In order to show how to get a value, I had to initialize the dictionary with key/value pairs. This returns the value associated with the “Bob” key and … Read more

C# – Initialize a dictionary

You can declare a dictionary and initialize it with values by using the collection initializer syntax. Within the initializer block, you have two options for adding key/value pairs to the dictionary: I’ll show examples of both options below. Note: If you have a list of items already, you can convert the list to a dictionary … Read more

C# – How to sort a dictionary

Dictionaries are unordered data structures. Key/value pairs aren’t stored in sorted order. When you want the Dictionary in sorted order, there are two simple options: I’ll show both options. Sort Dictionary with OrderBy() Use OrderBy() (from System.Linq) to sort the Dictionary by key or value. It returns the Dictionary’s KeyValuePairs in ascending sorted order. I’ll … Read more

C# – Filter a dictionary

The simplest way to filter a dictionary is by using the Linq Where() + ToDictionary() methods. Here’s an example: Note: You can use the Dictionary constructor (new Dictionary<string, int>(filterList)) instead of ToDictionary() if you prefer. This produces a new dictionary with the filtered item: Where() produces a list (actually an IEnumerable) of KeyValuePair objects. Most … Read more

C# – Change a dictionary’s values in a foreach loop

In .NET 5 and above, you can loop through a dictionary and directly change its values. Here’s an example: This outputs the following: You couldn’t do this before .NET 5, because it would invalidate the enumerator and throw an exception: InvalidOperationException: Collection was modified; enumeration operation my not execute. Instead, you’d have to make the … Read more

C# – Get key with the max value in a dictionary

The simplest way to get the key with the max value in a dictionary is to use the Linq MaxBy() method (added in .NET 6). This returns the key/value pair with the max value. Here’s an example: Note: All examples shown initialize the dictionary with a small number of key/value pairs for readability. This outputs … Read more

C# – Deserialize JSON using different property names

When JSON property names and class property names are different, and you can’t just change the names to match, you have three options: These options affect both deserialization and serialization. Let’s say you have the following JSON with camel-cased property names: Here’s an example of using the JsonPropertyName attribute: Note: The Newtonsoft equivalent is [JsonProperty(“title”)] … Read more

C# – Case insensitive dictionary

Dictionaries with string keys are case sensitive by default. If you want a case-insensitive dictionary, use the Dictionary constructor that takes a string comparison option and pass in StringComparer.InvariantCultureIgnoreCase, like this: Note: There are other case-insensitive options you can pick from, such as OrdinalIgnoreCase. Example I have a table that maps users to devices. The … Read more

KeyNotFoundException: The given key was not present in the dictionary

Problem The following exception is thrown when you try to get a value from a dictionary using a key that doesn’t exist in the dictionary: KeyNotFoundException: ‘The given key was not present in the dictionary.’ Consider the following the example of initializing a dictionary with a few key/value pairs, and then trying to access non-existent … Read more