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# – Get temp folder path and create a temp file

You can use Path.GetTempPath() to get the user’s temp folder path. Here’s an example: I’m running this in Windows, so it outputs my temp folder path: Path.GetTempPath() gets the temp folder path by checking environment variables (TMP, TEMP, USERPROFILE). It falls back to returning the system temp folder. Create a temp file Once you have … Read more

C# – Validate an IP address

Use IPAddress.Parse() to parse an IP address from a string. This handles both IPv4 and IPv6 addresses and throws an exception if the string can’t be parsed into a valid IP address. Here’s an example: This outputs the following: Use IPAddress.TryParse() if you don’t want exceptions to be thrown. It returns false if the string … Read more

C# – Ignore case with string.Contains()

By default, string.Contains() does a case sensitive search for a substring (or character) in a string. You can make it do a case insensitive search instead by passing in StringComparison.OrdinalIgnoreCase, like this: Note: StringComparison has three ‘ignore case’ options to choose from. Because this is doing a case insensitive search, it matched “earth” to “Earth” … Read more

C# – Get all files in a folder

There are two simple ways to get all files in a folder: I’ll show examples below, along with a few other scenarios, such as getting files from subfolders. Note: ‘directory’ and ‘folder’ mean the same thing. I use these terms interchangeably. Get all files with Directory.GetFiles() Directory.GetFiles() returns all file paths from the top-level folder … Read more

C# – Convert JSON to an object

Converting a JSON string to an object is referred to as deserialization. You can do this with a JSON serializer. There are two primary options: I’ll show examples by deserializing the following Movie JSON to a Movie object: Movie JSON: Movie class (properties match JSON): Using JsonSerializer.Deserialize() (in System.Text.Json) To deserialize with the built-in JsonSerializer.Deserialize(), … Read more

C# – Find a character in a string

There are three methods you can use to find a character in a string: I’ll show examples below. Using string.IndexOf() to find a character string.IndexOf() returns the index of the first occurrence of a character in a string. It searches the string from left to right, starting at the beginning. If it doesn’t find the … Read more

C# – Serialize to JSON in alphabetical order

There are two ways to serialize an object’s properties to JSON in alphabetical order using System.Text.Json: I’ll show how to do these two options below. Option 1 – Manually alphabetize with JsonPropertyOrder You can specify the exact serialization ordering by using the JsonPropertyOrder attribute. Therefore, to serialize in alphabetical order, first arrange the properties in … Read more

C# – Remove spaces from a string

The simplest way to remove spaces from a string is by using string.Replace(). Here’s an example: This outputs the following. Notice the spaces are removed. string.Replace() is good for removing all occurrences of a specific character (” ” in this case). When you want to remove all whitespace characters (spaces, tabs, newlines, etc..), there are … Read more

C# – Remove first or last character from a string

Use string.Remove() to remove character(s) from a string based on their index, such as the first or last character. This method has two parameters: string.Remove() returns a new string with the characters removed. I’ll show examples below. Remove the first character from a string To remove the first character, use string.Remove(startIndex: 0, count: 1), like … Read more