List<T>.Sort() / Reverse() / ForEach()
| Since: | C# 2.0(2005) |
|---|
The Sort(), Reverse(), and ForEach() methods for sorting a list, reversing the order of elements, and executing an action on every element.
Syntax
using System.Collections.Generic; // Sorts the list in ascending order using the default comparer (modifies the original list). list.Sort() // Sorts the list using a comparison function specified with a lambda expression. list.Sort(Comparison<T> comparison) // Reverses the order of elements in the list (modifies the original list). list.Reverse() // Executes an action on every element in the list. list.ForEach(Action<T> action)
Method List
| Method | Description |
|---|---|
| Sort() | Sorts the list's elements in ascending order using the default comparison. The original list is modified. |
| Sort(Comparison<T> comparison) | Sorts the list using a comparison function such as a lambda expression. |
| Reverse() | Reverses the order of all elements in the list. The original list is modified. |
| ForEach(Action<T> action) | Executes an action on each element. Equivalent to a foreach statement, but can be written more concisely with a lambda expression. |
Sample Code
Use Sort() to sort in ascending order, Reverse() for descending order, and ForEach() to process all elements with a lambda expression.
Program.cs
using System;
using System.Collections.Generic;
List<int> scores = new List<int> { 78, 92, 45, 88, 61 };
scores.Sort();
Console.WriteLine(string.Join(", ", scores)); // 45, 61, 78, 88, 92
scores.Reverse();
Console.WriteLine(string.Join(", ", scores)); // 92, 88, 78, 61, 45
scores.ForEach(p => Console.Write(p + " "));
Console.WriteLine();
This produces the following output:
dotnet run 45, 61, 78, 88, 92 92, 88, 78, 61, 45 92 88 78 61 45
Sorting with a Custom Comparison
Passing a lambda expression to Sort() lets you sort by any condition. A negative return value means a comes first; a positive return value means b comes first. Using CompareTo() keeps the code concise.
CustomSortSample.cs
using System;
using System.Collections.Generic;
List<string> names = new List<string> { "Okabe Rintaro", "Shiina Mayuri", "Makise Kurisu", "Hashida Itaru" };
// Sort by string length, shortest first
names.Sort((a, b) => a.Length.CompareTo(b.Length));
names.ForEach(n => Console.WriteLine(n));
This produces the following output:
dotnet run Hashida Itaru Shiina Mayuri Makise Kurisu Okabe Rintaro
Elements of equal length may appear in different order depending on the environment. List.Sort() does not guarantee a stable sort.
Preserving the Original List Before Sorting
Sort() and Reverse() modify the original list in place. To keep the original order, create a copy using new List<T>() and sort the copy instead.
PreserveSample.cs
using System;
using System.Collections.Generic;
List<int> original = new List<int> { 3, 1, 4, 1, 5, 9 };
List<int> sorted = new List<int>(original);
sorted.Sort();
Console.WriteLine(string.Join(", ", original)); // 3, 1, 4, 1, 5, 9 (unchanged)
Console.WriteLine(string.Join(", ", sorted)); // 1, 1, 3, 4, 5, 9
This produces the following output:
dotnet run 3, 1, 4, 1, 5, 9 1, 1, 3, 4, 5, 9
Common Mistakes
Common Mistake: break and continue Cannot Be Used Inside ForEach()
Lambda expressions inside ForEach() do not support break or continue. If you need to exit the loop early, use a regular foreach statement instead.
using System;
using System.Collections.Generic;
// NG: break is not allowed inside ForEach() (compile error)
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// numbers.ForEach(n => {
// if (n == 3) break; // CS0139: No enclosing loop out of which to break or continue
// Console.WriteLine(n);
// });
The corrected version looks like this:
using System;
using System.Collections.Generic;
// OK: use a regular foreach statement
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int n in numbers)
{
if (n == 3) break;
Console.WriteLine(n);
}
This produces the following output:
dotnet run 1 2
Notes
Both Sort() and Reverse() modify the original list in place. If you need to preserve the original list, create a copy first using new List<T>(originalList) before calling these methods.
ForEach() lets you write a foreach loop concisely with a lambda expression, but you cannot use break or continue inside it. If you need to exit the loop early, use a regular foreach statement instead.
For adding and removing list elements, see List<T>.Add() / Remove() / Clear().
If you find any errors or copyright issues, please contact us.