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# – 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# – 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 duplicates from a list

The simplest (and most efficient) way to remove duplicates from a list is by iterating, keeping track of items you’ve seen with a HashSet, and discarding items you’ve already seen. I’ll show four ways to implement this O(n) algorithm. At the end, I’ll explain a few inefficient approaches to avoid. Remove duplicates with ToHashSet() and … Read more

C# – Convert an array to a list

The simplest way to convert an array to a list is with the ToList() Linq method: This outputs the following: Besides using ToList(), you can also use the list constructor or AddRange(). Before I show those, I’ll explain why you’d want to use these special methods instead of just adding items individually to a new … Read more

C# – How to sort a list

When you need to sort a list, you don’t need to reinvent the wheel. You can use one of these three built-in methods for sorting a list: In this article, I’ll show examples of using these three approaches for sorting a list. Sort a list with OrderBy() (Linq) The OrderBy() Linq method generates an IOrderedEnumerable … 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

C# – Examples of using GroupBy() (Linq)

Here’s an example of using the Linq GroupBy() method to group coders by language: This example outputs the following: GroupBy() produces groups that contain the grouping key (i.e. Language) and the list of objects in the group (i.e. the Coder objects). The GroupBy() syntax is complex because it supports many scenarios. You can select one … Read more

C# – Remove a list of characters from a string

When you want to remove a list of characters from a string, loop through the list and use string.Replace(): Note that string.Replace() returns a new string (because strings are immutable). Running this outputs the following: This is the fastest approach (in .NET 6+). Linq approach: Where() + ToArray() + new string() Another option for removing … Read more

C# – Set operations with Linq

In this article, I’ll explain four set operations – intersection, union, difference, and symmetric difference – and how to perform these operations using Linq methods (such as Intersect()). These methods work on any type that implements IEnumerable – such as lists, arrays, and sets. Set intersection with Intersect() The intersection of set A {1,2} and … Read more

C# – Cannot use a lambda expression as an argument to a dynamically dispatched operation

Problem You are trying to use a lambda expression on a dynamic object and get the following compiler error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. As an example, the following code causes this error: Solution Cast the … Read more

Error: Sequence contains no elements

Problem When you call .First() on an empty IEnumerable, you get the following exception: System.InvalidOperationException: Sequence contains no elements Solution Option 1 – Use .FirstOrDefault() instead of .First() When the IEnumerable is empty, .FirstOrDefault() returns the default value for the type. For reference types this returns null. For value types this returns 0 or that … Read more

Could not find an implementation of the query pattern for source type

Problem Any time you try to use a Linq extension method (such as Select() to transform list elements) and you haven’t added ‘using System.Linq’, you’ll get a compiler error like this: Could not find an implementation of the query pattern for source type ‘Your Type’.  ‘Select’ not found. In newer versions, the error looks like … Read more