排序操作
排序操作基於一個或多個屬性對序列的元素進行排序。
排序依據
按升序對值進行排序。
方法語法
// 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 }
查詢語法
// 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
按降序對值進行排序。
方法語法
// 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 }
查詢語法
// 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
按升序執行輔助排序。
方法語法
// 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" }
查詢語法
// 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
按降序執行輔助排序。
方法語法
// 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" }
查詢語法
// 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
var numbers = new int[] { 1, 2, 3, 4, 5 };
var reversed = numbers.Reverse();
// reversed = { 5, 4, 3, 2, 1 }
查詢語法
// Not applicable.