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 specified 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 … 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

C# – Remove a set of characters from a string

The fastest and simplest way to remove a set of characters from a string is to use StringBuilder + List<char>, like this: I compared this with three other approaches. I did 100,000 iterations with a string with 2500 characters and a list of 15 characters to remove. This StringBuilder approach is almost 2x faster than … 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