C# – Parsing a CSV file

In this article, I’ll show how to parse a CSV file manually and with a parser library (CsvHelper). Let’s say you have the following CSV file: To manually parse this, read the file line by line and split each line with a comma. This gives you a string array containing the fields that you can … Read more

C# – Use yield return to minimize memory usage

Let’s say you want to search for specific characters in a large text file and return a list of context objects to the calling code for further processing (such as showing the results in the UI). One way to do that is to build the entire list at once and return it. If you don’t … 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# – Select distinct objects based on a property with Linq

There are three ways to select distinct objects based on a property using Linq methods: These select one movie per year: The simplest option is using GroupBy() because it doesn’t require any additional code. Distinct() is faster but it’s more complicated. DistinctBy() is the fastest and simplest, but requires the most code (it requires .NET … Read more

C# – Check if a string contains any substring from a list

There are many different scenarios where you might want to check a string against a list of substrings. Perhaps you’re dealing with messy exception handling and have to compare the exception message against a list of known error messages to determine if the error is transient or not. When you need to check a string … 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# – Parameterized tests in xUnit

Here’s an example of adding a parameterized unit test in xUnit: To parameterize a unit test, you have to do three things: If you’re used to doing parameterized tests with MSUnit, [Theory] is equivalent [DataMethod], and [InlineData] is equivalent to [DataRow]. In the rest of the article, I will show how to add parameterized tests … Read more