LINQ 中的排序运算符
排序操作允许基于一个或多个属性对序列中的元素进行排序。
运算符 | 描述 | C# 查询表达式语法 | VB 查询表达式语法 |
---|---|---|---|
OrderBy | 运算符按照升序对值进行排序 | orderby | Order By |
OrderByDescending | 运算符按照降序对值进行排序 | orderby ... descending | Order By ... Descending |
ThenBy | 按照升序执行二次排序 | orderby …, … | Order By …, … |
ThenByDescending | 按照降序执行二次排序 | orderby …, … descending | Order By …, … Descending |
Reverse | 对集合中元素的顺序进行反转 | 不适用 | 不适用 |
OrderBy、OrderByDescending 的示例 - 查询表达式
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class Program { static void Main(string[] args) { int[] num = { -20, 12, 6, 10, 0, -3, 1 }; //create a query that obtain the values in sorted order var posNums = from n in num orderby n select n; Console.Write("Values in ascending order: "); // Execute the query and display the results. foreach (int i in posNums) Console.Write(i + " \n"); var posNumsDesc = from n in num orderby n descending select n; Console.Write("\nValues in descending order: "); // Execute the query and display the results. foreach (int i in posNumsDesc) Console.Write(i + " \n"); Console.ReadLine(); } } }
VB
Module Module1 Sub Main() Dim num As Integer() = {-20, 12, 6, 10, 0, -3, 1}; Dim posNums = From n In num Order By n Select n; Console.Write("Values in ascending order: "); For Each n In posNums Console.WriteLine(n) Next Dim posNumsDesc = From n In num Order By n Descending Select n; Console.Write("Values in descending order: "); For Each n In posNumsDesc Console.WriteLine(n) Next Console.ReadLine() End Sub End Module
在 C# 或 VB 中编译并执行以上代码时,会产生以下结果 -
Values in ascending order: -20 -3 0 1 6 10 12 Values in descending order: 12 10 6 1 0 -3 -20
在 Thenby 和 ThenbyDescending 运算符中,可应用相同的语法,排序顺序将取决于多个列。优先级将是首先维护的列。
linq_query_operators.htm
广告