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# – Deserialize JSON to a dictionary

I’ll show examples of how to deserialize JSON to dictionaries in different scenarios. Deserializing to Dictionary<string, string> When your JSON object has properties with simple string values (as opposed to nested objects), you can deserialize to Dictionary<string, string>. Here’s an example. Consider the following simple JSON object: Note: In all examples, I’ll show the pretty-printed … Read more

C# – Serialize a dictionary to JSON

When you want to convert a dictionary to a JSON string, you can use the built-in JsonSerializer (from System.Text.Json) to serialize the dictionary. Here’s an example: Note: This is passing in WriteIndented=true to pretty print the JSON string for readability. This serializes the dictionary to a JSON string with the following format: I’ll show more … 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

C# – Update value in a dictionary

After you add a key/value pair to a dictionary, you can update the value for the key by using the indexer syntax (i.e. dictionary[key]=value), like this: This outputs the updated value for the ‘Bob’ key: The indexer syntax inserts if the key doesn’t exist -or- updates the value if the key already exists. This means … 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# – Add to a dictionary

The simplest way to add a key/value pair to a dictionary is by using Dictionary.Add(), like this: If the key already exists, Dictionary.Add() throws an ArgumentException because the key must be unique. There are a few other ways to add to a dictionary in different scenarios, which I’ll explain below. Add or update key/value in … 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# – Loop through a dictionary

The simplest way to loop through a dictionary is with a foreach loop. Here’s an example of initializing a dictionary with values and then looping through it: This outputs the following: The loop variable is a KeyValuePair<string, int> with Key and Value properties. Instead of using this, you can deconstruct the KeyValuePair into named variables, … Read more

C# – Convert a list to a dictionary

The simplest way to convert a list to a dictionary is to use the Linq ToDictionary() method: This loops through the list and uses the key/element selector lambdas you passed in to build the dictionary. In this article, I’ll go into details about how to use ToDictionary() and show how to deal with duplicate keys. … Read more

C# – Merge two dictionaries in-place

When you merge two dictionaries, you can either merge them in-place, or create a new dictionary and copy the values over to it. The following extension method does an in-place merge of two dictionaries. It loops through items in the right dictionary, adding them to the left dictionary. When duplicate keys exist, it’s keeping the … 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