Stable and Unstable Sorting for Structs in .NET
03/16/2024
Sorting items of a collection is a common task that .NET developers perform. A collection is a data structure that stores multiple values, such as an array, a list, a dictionary, etc.
One common way to sort items of a collection in .NET 8 (and previous .NET versions) is by using LINQ’s OrderBy
extension method. LINQ stands for Language Integrated Query, and it is a set of features that allow you to query and manipulate data in various ways. For example, you can use OrderBy
to sort a list of numbers:
// Create a list of numbers List<int> numbers = [3, 1, 2]; // Sort the list using OrderBy var sorted = numbers.OrderBy(x => x);
Another way to sort items of a collection is by using Array.Sort
method. This method works on arrays, which are fixed-size collections of values. For example, you can use Array.Sort
to sort an array of numbers in ascending order: