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# – Convert a dictionary to a list

The simplest way to convert a dictionary to a list is by using the Linq ToList() method, like this: When used on a dictionary, ToList() returns a list of KeyValuePair objects. This example outputs the following: Dictionary keys to list If you want a list of the dictionary’s keys, use ToList() on Dictionary.Keys, like this: … 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# – 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# – 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# – 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# – 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

C# – Get int value from enum

The simplest way to get an enum’s int value is by casting it to an int. Here’s an example: This outputs the following: When the enum is generic (of type ‘Enum’) You can’t cast a generic ‘Enum’ to int, otherwise you get a compiler error (CS0030 Cannot convert type ‘System.Enum’ to ‘int’). Use Convert.Int32() instead. … Read more

C# – How to convert char to int

Converting a char to an int means getting the numeric value that the char represents (i.e. ‘1’ to 1). This is not the same as casting the char to an int, which gives you the char’s underlying value (i.e. ‘1’ is 49). There are three ways to convert a char to an int: I’ll show … Read more

C# – Remove items from a list while iterating

There are two ways to iterate through a List<T> and remove items based on a condition: These remove items from the list in an in-place manner (i.e. modify the original list) and avoid the problems you run into when doing this incorrectly (such as using a foreach or looping forward). I’ll show examples below. Then … 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# – How to deconstruct tuples

Deconstructing a tuple means assigning its fields to several variables at once by using the deconstruction assignment syntax. This is also referred to as destructuring or tuple unpacking. Here’s an example of deconstructing a tuple into two variables: This outputs: Deconstructing the tuple assigns the fields (Item1 and Item2) to variables based on position. The … Read more

C# – How to use named tuples

You can use tuples to contain multiple values and pass them around. By default, the tuple field names are unfriendly – Item1, Item2, etc… Instead of using these default names, you can name the tuple fields. Here’s an example of creating and using a named tuple: Meaningful names makes tuples easier to use. movieTuple.title is … Read more

ASP.NET Core – Client-side custom validation attributes

I wrote about how to add custom validation attributes. These are used for model validation on the server-side. You can also use these for client-side validation, which I’ll show in this article. 1 – Implement IClientModelValidator The first step is to implement the IClientModelValidator interface in the custom validation attribute class. This has a single … Read more

C# – How to parse XML with XElement (Linq)

Use the XElement class (from the Linq-to-Xml API) to parse XML and work with it in memory. You can use this to search for XML elements, attributes, and modify values. This is an alternative to using an XML (de)serializer (which requires you to define a class that matches the XML structure). I’ll show examples of … Read more

C# – Read XML element attributes with XElement (Linq)

XML elements can have attributes, which are key-value pairs. To read the attributes, use XElement to parse the XML string (from the Linq-to-Xml API). Then you can use these two methods for getting attributes: Once you have the attributes, use the XAttribute.Value property to read the attribute’s string value. Here’s an example of getting all … Read more

CsvHelper – Header with name not found

When your CSV header names don’t match your property names exactly, CsvHelper will throw an exception. For example, if your header name is “title” and your property name is “Title”, it’ll throw an exception like: HeaderValidationException: Header with name ‘Title'[0] was not found. If you don’t want to (or can’t) change the names to match, … Read more

C# – Using CsvHelper when there’s no header row

When you’re parsing CSV with CsvHelper and there’s no header row, you have to configure it to map by field position. I’ll show how to do that. At the end, I’ll show the alternative approach of manually parsing in this scenario. Consider the following CSV data without a header row: Normally, CsvHelper maps fields to … Read more