C# – Dictionary with multiple values per key

Each dictionary key maps to exactly one value. When you want multiple values per key, you can use a dictionary of lists. Here’s an example of creating a dictionary of lists, where each key maps to multiple ints: Notice that you can add to the dictionary like normal. The difference with a dictionary of lists … Read more

C# – Using String.Join()

You can use String.Join() to convert a collection of items to a string with a separator (such as a comma). Here’s an example of using String.Join() to convert a List of strings to a comma-separated string: This results in the following comma-separated string: String.Join() can be used on wide variety of input: I’ll show a … Read more

C# – Convert a List to a string

There are two good ways to convert a List<T> to a string: I’ll show examples of both approaches. Using String.Join() String.Join() is the simplest way to convert a List to a string. With this method, you pass in the List and a delimiter and it outputs a string. You can use any delimiter you want. … 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# – Remove items from a list

Here are the different ways to remove items from a list: I’ll show examples of using these methods. Remove item by index with List.RemoveAt() You can use List.RemoveAt() to remove an item at an index (0-based). Here’s an example of removing the first and last item from the list: This removes the first item “A” … Read more

C# – Convert string list to int list

You can convert a list of strings to a list of integers by using int.Parse() on all of the strings. There are two simple ways to do this: I’ll show examples of these using these methods and then explain how to handle parsing exceptions. Option 1 – Use List.ConvertAll() Here’s an example of how to … 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# – Convert list to array

The simplest way to convert a list to an array is to use the List.ToArray() method: This outputs the following: Internally, the List<T> class stores elements in a dynamically sized array (it resizes when necessary). So under the hood, List.ToArray() uses Array.Copy() to copy the list’s internal array to a new array. This is very … Read more

HackerRank – Zig Zag Sequence solution

In this article, I’ll explain the Zig Zag Sequence algorithm problem on HackerRank. Problem statement: You’re given an integer array with an odd number of elements (ex: [5, 2, 3, 1, 4]). You need to re-arrange the elements so they’re in a zig zag sequence, which means: Here’s a diagram to help you visualize what … Read more

ASP.NET Core – How to get request headers

There are two ways to get request headers: When a request comes in, the framework loads request headers into the Request.Headers dictionary. You can use this just like any other dictionary. Here’s an example of using TryGetValue() to check if a request header exists and get its value: Note: To just check if a header … 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# – Save a list of strings to a file

The simplest way to save a list of strings to a file is to use File.WriteAllLines(). This creates (or overwrites) the file and writes each string on a new line. The resulting file looks like this: Note: Showing non-printable newline characters \r\n for clarity. Specifying the separator character What if you want to separate each … Read more

C# – How to batch read with Threading.ChannelReader

In a consumer/producer scenario, there are many reasons why you might want the consumer to read a batch of items. Maybe you’re bulk inserting into the database, or sending a payload with HttpClient. Sending lots of individual items over the network can be costly, and waiting for a full batch of items before sending is … Read more

C# – Join strings with a separator, ignoring nulls and empty strings

Normally when you want to join strings using a separator, you’d use string.Join(). However, the problem with string.Join() is it doesn’t ignore nulls or empty strings. Take a look at the following examples: If you want to filter out nulls and empty strings, you can filter the list of strings yourself and pass it into … Read more

C# – Convert a list of strings into a set of enums

Let’s say you have a list of HTTP status codes that you read in when the service starts up (perhaps from appsettings.json or from the database). Whenever you send an HTTP request, you want to check if the returned status code is in this list of status code. To make things more efficient, you want … 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# – Hex string to byte array

This article shows code for converting a hex string to a byte array, unit tests, and a speed comparison. First, this diagram shows the algorithm for converting a hex string to a byte array. To convert a hex string to a byte array, you need to loop through the hex string and convert two characters … Read more

C# – Log every method call

I want to log method calls, including their parameter names and values, and what called the method. I want to minimize the amount of coding involved. For example: What options are available? In this article I’ll explain how to use the simple built-in approach. 1 – Create LogMethodCall() utility method The System.Diagnostics.StackFrame class gives us … Read more

WinForms – How to get CheckedListBox selected values

A CheckedListBox is a list control with multiple checkboxes. This allows the user to check multiple boxes at once. You can also programmatically check items in the CheckedListBox and remove them. How can I can get all the values they selected? By looping through the CheckedListBox.CheckedItems collection. See the UI and Code examples below. UI … Read more

C# – Parsing CSV data when a field has commas

When you have commas in your CSV fields, it creates a conflict with the field delimiting commas. In other words, you can’t tell which data belongs to which field. How you deal with this will depend on one question: is the field with the comma enclosed in quotes? Comma is enclosed in quotes Spreadsheet programs … Read more