OverflowException: Value was either too large or too small for an int32

Problem When you try to convert a string to an integer with int.Parse() (or Convert.ToInt32()), you get the following exception: System.OverflowException: Value was either too large or too small for an Int32. The problem is the integer value in the string can’t fit in the 32-bit integer. Int32 (int) can only hold values between -2147483648 … Read more

C# – Get key with the max value in a dictionary

The simplest way to get the key with the max value in a dictionary is to use the Linq MaxBy() method (added in .NET 6). This returns the key/value pair with the max value. Here’s an example: Note: All examples shown initialize the dictionary with a small number of key/value pairs for readability. This outputs … 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