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# – How to use LinkedList

LinkedList<T> is a doubly linked list. It consists of nodes with values (i.e. integers, strings, etc…) and links to the next and previous node. LinkedList<T> has a reference to the head and tail nodes, which enables efficient insertion (and removal) from the start and end of the list. The main reason to use LinkedList<T> is … 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# – 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 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

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# – Using a list of tuples

Here’s an example of how to initialize a list of named tuples: This creates a list of named value tuples (ValueTuple<string, int>) using list initializer syntax and then loops through the tuples. I suggest always using named value tuples (not System.Tuple). This outputs the following: I’ll now show how to add to the list of … Read more

C# – Delete records with Dapper

You can delete records with Dapper by using Execute() with a DELETE statement and specifying the record ID as a parameter. Here’s an example: This deletes a single record from the Movies table. Delete multiple records When you’re deleting multiple records, you can efficiently execute a single DELETE statement with a WHERE clause including all … Read more

C# – Parse a comma-separated string into a list of integers

Let’s say you want to parse a comma-separated string into a list of integers. For example, you have “1,2,3” and you want to parse it into [1,2,3]. This is different from parsing CSV with rows of comma-separated values. This is more straightforward. You can use string.Split(“,”) to get the individual string values and then convert … Read more

C# – Deserialize a JSON array to a list

When you’re working with a JSON array, you can deserialize it to a list like this: This deserializes all of the objects in the JSON array into a List<Movie>. You can use this list object like usual. Note: All examples will use System.Collections.Generic and System.Text.Json. I’ll exclude the using statements for brevity. Example – JSON … 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

Collection was modified; enumeration operation may not execute

If you try to add/remove items from a collection while it’s being looped over in a foreach loop (enumerated), then you’ll get the following exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.at System.Collections.Generic.List`1.Enumerator.MoveNext() This error can happen in two scenarios: The solution to this problem depends on which scenario you’re in. In this … Read more

C# – Using the DynamicData attribute in unit tests

The purpose of parameterized tests is to eliminate duplicated tests. There are two ways to pass parameters into a parameterized test: the DataRow attribute and the DynamicData attribute. With DataRow, the problem is you can only pass in constants and arrays. You can’t pass in reference types. When you try to pass in reference types, … 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