How to sort a List in C#
In C#, you can use the Sort
method to sort a List
in ascending order. Here's an example of how you can sort a list of integers:
List<int> numbers = new List<int> { 4, 2, 7, 1, 9 }; numbers.Sort();
After executing the Sort
method, the numbers
list will be sorted in ascending order: { 1, 2, 4, 7, 9 }
.
If you want to sort a list of objects based on a specific property, you can use the Sort
method with a custom comparison. Here's an example where we sort a list of Person
objects based on their Name
property:
class Person { public string Name { get; set; } // other properties } List<Person> people = new List<Person> { new Person { Name = "Alice" }, new Person { Name = "Charlie" }, new Person { Name = "Bob" } }; people.Sort((p1, p2) => p1.Name.CompareTo(p2.Name));
After executing the Sort
method with the custom comparison, the people
list will be sorted alphabetically by name: { "Alice", "Bob", "Charlie" }
.
Alternatively, if you want to sort a list in descending order, you can use the Sort
method with a custom comparison and reverse the result using the Reverse
method:
List<int> numbers = new List<int> { 4, 2, 7, 1, 9 }; numbers.Sort((x, y) => y.CompareTo(x)); numbers.Reverse();
numbers
list will be sorted in descending order: { 9, 7, 4, 2, 1 }
.