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

在Tenby和ThenbyDescending運算子,同樣的語法可以應用排序,順序將取決於列位置。第一列為優先。