
You want to use a query expression to sort from lowest to highest value in your C# program. The ascending keyword, which specifies the default sorting order in an explicit way, can be used for this. It can be used to improve program clarity.
This C# article uses the ascending keyword in a query expression.
This program creates an array of Employee object instances. Next, it uses a query expression to sort these object instances from high to low Salary. If two objects have the same Salary, they are again sorted from low to high Id.
Program that uses ascending sort [C#]
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, 4Sorting on multiple properties. Query expressions provide a very intuitive syntax for sorting on two properties at once. The first property specified in the orderby clause is the primary sort; the second is the secondary sort that is only activated when a conflict occurs.
OrderBy Clause
Because ascending is the default sort order, you don't actually need to use it when you want to sort. You can just omit ascending and the query expression will function the same way. The reason you may want to use ascending is that it makes explicit the distinction between descending and ascending. So if you have a descending sort elsewhere, specifying ascending makes clear your goal.
Descending KeywordQuery expressions in the C# language introduce a powerful syntax for sorting collections. With ascending and descending, you can make clear your demands for sorting the elements in your collections.
LINQ Examples