In C#, List.Sort() puts the items of the list in order. It changes the same list; it does not make a new one. With no arguments it uses the default order of the item type: smallest to largest for numbers, and alphabetical for strings.
For any other order you give it a rule. A Comparison<T> lambda such as (a, b) => b.CompareTo(a) takes two items and returns a negative number, zero, or a positive number to say which goes first. A comparer class (IComparer<T>) does the same job when you want to reuse the rule. After sorting, BinarySearch() becomes possible.
This is an instance member of List<T> (System.Collections.Generic). Call it on a list variable, such as numbers.Sort(...). A List<T> is a class, so two variables can share one list. It keeps items in the order you put them, allows duplicates, and grows when needed. An array, by comparison, has a fixed length.
Syntax
Call it with no arguments for the default order, or pass a rule. The list itself is reordered.
A lambda that puts bigger items first (descending).
items.Sort(new MyComparer())
A comparer class that implements IComparer<T>.
Sort is not stable: items that the rule treats as equal may end up in a different order than they had before. When that matters, add a tie-break to your rule (such as comparing names when scores are equal). The sort is O(n log n). If your item type has no default order and you give no rule, Sort() throws InvalidOperationException. Array.Sort is the static version for arrays.
Library declarations
C#
public void Sort();
public void Sort(Comparison<T> comparison);
public void Sort(IComparer<T> comparer);
public void Sort(int index, int count, IComparer<T> comparer);
Parameters
Parameter
Description
comparison
Optional overload. A Comparison<T> lambda that returns less than 0, 0, or more than 0 for two items.
comparer
Optional overload. An IComparer<T> object. null means the default order.
index, count
Optional overload. Sort only count items that start at index.
Return Value
Return Value
Description
void
Nothing is returned. The list is reordered in place and Count does not change.
C# Examples
Example 1 — Sort Numbers and Names
Use Sort() with no arguments on a list of numbers and a list of strings.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new List<int> { 30, 10, 20, 10 };
numbers.Sort();
Console.WriteLine(string.Join(", ", numbers));
List<string> names = new List<string> { "Dan", "Ann", "Cara", "Bob" };
names.Sort();
Console.WriteLine(string.Join(", ", names));
}
}
Output
10, 10, 20, 30
Ann, Bob, Cara, Dan
How It Works
Ascending by default. Numbers are placed from smallest to largest. The two 10 values end up next to each other.
Same list, new order.Sort returns nothing. The numbers variable now holds the sorted items.
Alphabetical strings. The default order of text is alphabetical, so "Ann" comes first and "Dan" last.
Mixed case is tricky. The default string order depends on the culture settings, and it can place "apple" and "Banana" differently from a plain code-point order. These examples use the same casing to stay predictable.
Example 2 — Sort with a Comparison Lambda
Sort numbers from big to small, then sort words by length with a tie-break so equal lengths come out alphabetically.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> scores = new List<int> { 70, 95, 82, 60 };
scores.Sort((a, b) => b.CompareTo(a));
Console.WriteLine(string.Join(", ", scores));
List<string> words = new List<string> { "pear", "fig", "apple", "kiwi", "date" };
words.Sort((a, b) => {
if (a.Length != b.Length) {
return a.Length.CompareTo(b.Length);
}
return string.CompareOrdinal(a, b);
});
Console.WriteLine(string.Join(", ", words));
}
}
Output
95, 82, 70, 60
fig, date, kiwi, pear, apple
How It Works
Swap the sides.a.CompareTo(b) sorts ascending. Writing b.CompareTo(a) flips it, so bigger numbers go first.
Two inputs, one answer. The lambda gets two items and returns a negative, zero, or positive number. Negative means a goes before b.
Primary rule. For the words, a shorter word comes first. "fig" has 3 letters, the four-letter words follow, and "apple" is last.
Tie-break rule. When the lengths match, CompareOrdinal orders the words alphabetically. That is why date, kiwi, pear appear in the same order every run, even though the sort is unstable.
Example 3 — Sort Objects with an IComparer
Put the rule in its own class so you can reuse it. Sort students by score from high to low, then by name.
C#
using System;
using System.Collections.Generic;
class Student {
public string Name;
public int Score;
}
class ByScoreThenName : IComparer<Student> {
public int Compare(Student a, Student b) {
int c = b.Score.CompareTo(a.Score);
if (c != 0) {
return c;
}
return string.CompareOrdinal(a.Name, b.Name);
}
}
class Program {
static void Main() {
List<Student> students = new List<Student> {
new Student { Name = "Ben", Score = 90 },
new Student { Name = "Dia", Score = 70 },
new Student { Name = "Chen", Score = 90 },
new Student { Name = "Asha", Score = 85 }
};
students.Sort(new ByScoreThenName());
foreach (Student s in students) {
Console.WriteLine(s.Name + " " + s.Score);
}
}
}
Output
Ben 90
Chen 90
Asha 85
Dia 70
How It Works
A class for the rule.ByScoreThenName implements IComparer<Student>, which has one method, Compare, that takes two students.
First rule: score.b.Score.CompareTo(a.Score) has the sides swapped, so a higher score goes first.
Second rule: name. Ben and Chen both have 90. Since c is 0, the method falls through to the name comparison, so "Ben" comes before "Chen".
Reusable. You can pass new ByScoreThenName() to other lists or to BinarySearch. The objects are the same ones as before, just in a new order.
Frequently Asked Questions
It sorts the items of the list in place, using the default order, or the order from the Comparison lambda or IComparer you pass.
No. Items that compare as equal may change their relative order. Add a tie-break rule, or use LINQ OrderBy, which is stable, when the original order of equal items matters.
Pass a lambda that swaps the sides: list.Sort((a, b) => b.CompareTo(a)). You can also call Sort() and then Reverse().
Use a Comparison lambda such as people.Sort((a, b) => a.Age.CompareTo(b.Age)), or write a class that implements IComparer<T>.
List.Sort changes the original list and is not stable. OrderBy creates a new sorted sequence, leaves the original alone, and is stable.