How to sort a list in C#
You can sort a list in C# using the Sort() method for in-place sorting, or LINQ's OrderBy() for creating a new sorted sequence. The Sort() method modifies the original list, while OrderBy() returns a new sorted IEnumerable<T>.
For descending order, use Sort() with a comparison delegate, or LINQ's OrderByDescending(). Custom sorting can be achieved with IComparer<T> or lambda expressions.
Sorting objects requires specifying which property to sort by using OrderBy(x => x.PropertyName) or implementing IComparable<T> on the class.
C# Example Code
using System;
using System.Collections.Generic;
using System.Linq;
public class SortList
{
public static void Main(string[] args)
{
// Sort numbers ascending
List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3 };
numbers.Sort(); // In-place sort
Console.WriteLine("Sorted numbers: " + string.Join(", ", numbers));
// Sort numbers descending
List<int> numbers2 = new List<int> { 5, 2, 8, 1, 9, 3 };
numbers2.Sort((a, b) => b.CompareTo(a)); // Reverse comparison
Console.WriteLine("Descending: " + string.Join(", ", numbers2));
// Sort strings alphabetically
List<string> names = new List<string> { "Charlie", "Alice", "Bob", "David" };
names.Sort();
Console.WriteLine("Sorted names: " + string.Join(", ", names));
// Using LINQ OrderBy (creates new sequence)
List<int> numbers3 = new List<int> { 5, 2, 8, 1, 9, 3 };
var sorted = numbers3.OrderBy(n => n).ToList();
Console.WriteLine("LINQ OrderBy: " + string.Join(", ", sorted));
// OrderByDescending
var descending = numbers3.OrderByDescending(n => n).ToList();
Console.WriteLine("LINQ Descending: " + string.Join(", ", descending));
// Sorting objects by property
List<Person> people = new List<Person>
{
new Person("Charlie", 35),
new Person("Alice", 25),
new Person("Bob", 30)
};
// Sort by name
var sortedByName = people.OrderBy(p => p.Name).ToList();
Console.WriteLine("\nSorted by name:");
foreach (var person in sortedByName)
{
Console.WriteLine($" {person.Name}: {person.Age}");
}
// Sort by age
var sortedByAge = people.OrderBy(p => p.Age).ToList();
Console.WriteLine("\nSorted by age:");
foreach (var person in sortedByAge)
{
Console.WriteLine($" {person.Name}: {person.Age}");
}
// Multiple sorting criteria
var multiSort = people.OrderBy(p => p.Age).ThenBy(p => p.Name).ToList();
Console.WriteLine("\nSorted by age, then name:");
foreach (var person in multiSort)
{
Console.WriteLine($" {person.Name}: {person.Age}");
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}