Stable and Unstable Sorts in .NET
03/09/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 names alphabetically:
// Create a list of names List<string> names = new List<string>() { "Charlie", "Alice", "Bob" }; // Sort the list by name using OrderBy var sortedNames = names.OrderBy(name => name);
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: