A sorting operation orders the elements of a sequence based on one or more attributes.
OrderBy
Sorts values in ascending order.
Method Syntax
// OrderBy
var numbers = new int[] { 5, 4, 8, 2, 7, 1, 9, 3, 6 };
var ordered = numbers.OrderBy(n => n);
// ordered = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
Query Syntax
// orderby
var numbers = new int[] { 5, 4, 8, 2, 7, 1, 9, 3, 6 };
var ordered = from n in numbers
orderby n
select n;
// ordered = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
OrderByDescending
Sorts values in descending order.
Method Syntax
// OrderByDescending
var numbers = new int[] { 5, 4, 8, 2, 7, 1, 9, 3, 6 };
var ordered = numbers.OrderByDescending(n => n);
// ordered = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }
Query Syntax
// orderby
var numbers = new int[] { 5, 4, 8, 2, 7, 1, 9, 3, 6 };
var ordered = from n in numbers
orderby n descending
select n;
// ordered = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }
ThenBy
Performs a secondary sort in ascending order.
Method Syntax
// ThenBy
string[] words = { "the", "quick", "brown", "fox", "jumps" };
var ordered = words.OrderBy(w => w.Length).ThenBy(w => w[0]);
// ordered = { "fox", "the", "brown", "jumps", "quick" }
Query Syntax
// orderby …, …
string[] words = { "the", "quick", "brown", "fox", "jumps" };
var ordered = from w in words
orderby w.Length, w[0]
select w;
// ordered = { "fox", "the", "brown", "jumps", "quick" }
ThenByDescending
Performs a secondary sort in descending order.
Method Syntax
// ThenByDescending
string[] words = { "the", "quick", "brown", "fox", "jumps" };
var ordered = words.OrderBy(w => w[0]).ThenByDescending(w => w.Length);
// ordered = { "brown", "fox", "jumps", "quick", "the" }
Query Syntax
// orderby …, … descending
string[] words = { "the", "quick", "brown", "fox", "jumps" };
var ordered = from w in words
orderby w.Length, w[0] descending
select w;
// ordered = { "the", "fox", "quick", "jumps", "brown" }
Reverse
Reverses the order of the elements in a collection.
Method Syntax
// Reverse
var numbers = new int[] { 1, 2, 3, 4, 5 };
var reversed = numbers.Reverse();
// reversed = { 5, 4, 3, 2, 1 }
Query Syntax
// Not applicable.