Linq-sorting-operators
提供:Dev Guides
LINQの演算子の並べ替え
ソート操作を使用すると、単一または複数の属性に基づいてシーケンスの要素を並べることができます。
Operator | Description | C# Query Expression Syntax | VB Query Expression Syntax |
---|---|---|---|
OrderBy | The operator sort values in an ascending order | orderby | Order By |
OrderByDescending | The operator sort values in a descending order | orderby … descending | Order By … Descending |
ThenBy | Executes a secondary sorting in an ascending order | orderby …, … | Order By …, … |
ThenByDescending | Executes a secondary sorting in a descending order | orderby …, … descending | Order By …, … Descending |
Reverse | Performs a reversal of the order of the elements in a collection | Not Applicable | Not Applicable |
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演算子では、同じ構文を適用でき、並べ替え順序は複数の列に依存します。 優先順位は、最初に維持される列になります。