LINQ 中的排序运算符

排序操作允许根据一个或多个属性对序列中的元素进行排序。

降序排序
运算符 描述 C# 查询表达式语法 VB 查询表达式语法
OrderBy 运算符按升序对值进行排序 orderby Order By
OrderByDescending 运算符按降序对值进行排序 orderby ... 降序排序 Order By ... 降序排序
ThenBy 按升序执行二次排序 orderby …, … Order By …, …
ThenByDescending 按降序执行二次排序 orderby …, … 降序排序 Order By …, … 降序排序
反转 对集合中元素的顺序进行反转 不适用 不适用适用

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 + " 
");

            var posNumsDesc = from n in num
                              orderby n descending
                              select n;
										
            Console.Write("
Values in descending order: ");

         // Execute the query and display the results.
		 
         foreach (int i in posNumsDesc) 
            Console.Write(i + " 
");

            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.html