Sorting Operators in LINQ
A sorting operation allows ordering the elements of a sequence on basis of a single or more attributes.
| 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 |
Example of OrderBy, OrderByDescending - Query Expression
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
When the above code in C# or VB is compiled and executed, it produces the following result −
Values in ascending order: -20 -3 0 1 6 10 12 Values in descending order: 12 10 6 1 0 -3 -20
In Thenby and ThenbyDescending operators, same syntax can be applied and sorting order will depend on more than one columns. Priority will be the column which is maintained first.
linq_query_operators.htm
Advertisements