Sorting Lists and Arrays in C#: Efficient Techniques Using `List.Sort()` and `Array.Sort()`
Learn how to efficiently sort lists and arrays in C#. This tutorial demonstrates using `List
Sorting Lists and Arrays in C#
Sorting Lists in Descending Order using `List.Sort()`
The C# `List
C# Code
using System;
using System.Collections.Generic;
public class ListSortExample {
public static void Main(string[] args) {
List<int> numbers = new List<int> { 53, 37, 64, 29, 49 };
numbers.Sort((a, b) => b.CompareTo(a)); // Sort in descending order
Console.WriteLine("Sorted List (Descending):");
foreach (int num in numbers) {
Console.Write($"{num} ");
}
}
}
The lambda expression `(a, b) => b.CompareTo(a)` compares two elements (`a` and `b`) in reverse order. The `CompareTo` method performs the comparison, and the result determines the order.
Sorting Arrays in Descending Order
Another approach to sorting in descending order is to first sort in ascending order (using `Array.Sort()`) and then reverse the array (using `Array.Reverse()`). This method is useful if your programming environment or library only supports ascending sorts.
1. Sorting in Ascending Order
The `Array.Sort()` method sorts an array in ascending order.
2. Reversing the Sorted Array
The `Array.Reverse()` method reverses the order of elements in an array.
Example: Sorting an Array in Descending Order
C# Code
using System;
public class ArraySortExample {
public static void Main(string[] args) {
int[] numbers = { 5, 2, 8, 1, 3 };
Array.Sort(numbers);
Array.Reverse(numbers);
Console.WriteLine("Sorted (Descending):");
foreach (int num in numbers) {
Console.Write($"{num} ");
}
}
}
Conclusion
C# provides several ways to sort data, offering flexibility based on your needs and data structure. Using custom comparison delegates with `List