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# – 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

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

WinForms – How to remove checked items from CheckedListBox

Normally the items in a CheckedListBox are hardcoded or added programmatically (from an enum or from binding a data source). But sometimes you may want to allow the user to add and remove items from a CheckedListItem. In this article I’ll show how to add items and remove them. I’ll be working with text, and … Read more

Multithreaded quicksort in C#

One day I decided to challenge myself by trying to implement multithreaded quicksort. I wanted to see how it would compare to the built-in Array.Sort() method. I came up with two algorithms that were 2-4x faster than Array.Sort(): After continuing to tinker, in attempts to further optimize, I came across the AsParallel().OrderBy() method (PLINQ). After … Read more