C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: We create an integer array of odd numbers. We will be sorting these elements with a query expression.
Part 2: The orderby clause here is translated into a method call to OrderByDescending.
OrderBy, OrderByDescendingPart 3: In the foreach, the query expression is evaluated and sorted. The int array elements are now ordered from largest to smallest.
String InterpolationC# program that uses descending keyword
using System;
using System.Linq;
class Program
{
static void Main()
{
// Part 1: create an integer array.
int[] array = { 1, 3, 5, 7, 9 };
// Part 2: select the elements in a descending order with query clauses.
var result = from element in array
orderby element descending
select element;
// Part 3: evaluate the query and display the results.
foreach (var element in result)
{
Console.WriteLine($"DESCENDING: {element}");
}
}
}
Output
DESCENDING: 9
DESCENDING: 7
DESCENDING: 5
DESCENDING: 3
DESCENDING: 1
So: You do not need to specify ascending to get an ascending sort. Query expression sorts are implicitly ascending.
However: The ascending keyword can provide a symmetry to the orderby clauses in your query expressions.
orderbyProgram: We create an array of Employee objects. We use a query expression to sort these objects from high to low Salary.
ArrayAlso: If two objects have the same Salary, they are again sorted from low to high Id.
C# program that uses ascending sort
using System;
using System.Linq;
class Employee
{
public int Salary { get; set; }
public int Id { get; set; }
}
class Program
{
static void Main()
{
Employee[] array = new Employee[]
{
new Employee(){Salary = 40000, Id = 4},
new Employee(){Salary = 40000, Id = 0},
new Employee(){Salary = 60000, Id = 7},
new Employee(){Salary = 60000, Id = 9}
};
// Highest salaries first.
// ... Lowest IDs first.
var result = from em in array
orderby em.Salary descending, em.Id ascending
select em;
foreach (var em in result)
Console.WriteLine("{0}, {1}", em.Salary, em.Id);
}
}
Output
60000, 7
60000, 9
40000, 0
40000, 4
And: The second is the secondary sort that is only activated when a conflict occurs.
And: It is in a sense a form of syntactic sugar. It makes explicit the distinction between descending and ascending.
Note: Query syntax was provided to allow for more natural syntax on declaration expressions.
Further: The descending contextual keyword here allows for a more natural language syntax for expressing the intent of the program.
Note: The execution engine only sees the intermediate language provided by the C# compiler. It does not detect the original syntax.