Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Ascending Keyword

This C# example program uses the ascending keyword in a query expression.

Ascending is a sort order. It specifies from low to high values.

It is the default sorting order in the C# language. But in query expressions we can specify ascending—this improves program clarity.

Example. 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.

Based on:

.NET 4.5

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


60000, 7
60000, 9
40000, 0
40000, 4

Sorting on multiple properties. Query expressions provide an intuitive syntax for sorting on two properties at once. The first property specified in the orderby clause is the primary sort.


And: The second is the secondary sort that is only activated when a conflict occurs.

Discussion. Because ascending is the default sort order, you don't actually need to use it when you want to sort. You can just omit this keyword and the query expression will function the same way. It is in a sense a form of syntactic sugar.

Tip: You may want to use ascending because it makes explicit the distinction between descending and ascending.

Tip 2: If you have a descending sort elsewhere, specifying ascending makes clear your goal.


Summary. Query 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.