# LINQ排序運算子

## 排序運算子

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

}
}
}```

### 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
End Sub
End Module```

```Values in ascending order: -20
-3
0
1
6
10
12
Values in descending order: 12
10
6
1
0
-3
-20```