C# – Use yield return to minimize memory usage

Let’s say you want to search through a large text file for specific characters 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# – Remove non-alphanumeric characters from a string

The simplest way to remove non-alphanumeric characters from a string is to use regex: Note: Don’t pass in a null, otherwise you’ll get an exception. Regex is the simplest approach for solving this problem, but it’s also the slowest. If you’re concerned about the performance take a look at the performance section below. This example … 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# – 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

System.InvalidOperationException: 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: You’re looping over the collection in a foreach loop and modifying it (add/removing) … Read more

WinForms: How to check if another form is open

If you’re working on a Windows Forms project and need to know which forms are open, use: This gives you an IEnumerable collection of form objects that are currently open. You can lookup a form by name, by type, or loop through the list. Example scenarios There are many scenarios where you’d want to know … Read more