C# LINQ Keywords - The orderby Clause

The orderby clause is used to sort the sequence of results in a query. Following the orderby keyword is the item you want to sort by, which is commonly some property of the range variable. You can sort in either ascending or descending order, and if you don’t specify that with either the ascending or descending keyword, ascending is the default order. Following the orderby clause, you can have an unlimited set of subsorts simply by separating each sort item with a comma, as demonstrated here:

using System;
using System.Linq;
using System.Collections.Generic;

public class Employee
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Nationality { get; set; }
}

public class OrderByExample
{
static void Main() {
var employees = new List() {
new Employee {
LastName = "Glasser", FirstName = "Ed",
Nationality = "American"
},
new Employee {
LastName = "Pupkin", FirstName = "Vasya",
Nationality = "Russian"
},
new Employee {
LastName = "Smails", FirstName = "Spaulding",
Nationality = "Irish"
},
new Employee {
LastName = "Ivanov", FirstName = "Ivan",
Nationality = "Russian"
}
};

var query = from emp in employees
orderby emp.Nationality,
emp.LastName descending,
emp.FirstName descending
select emp;
foreach( var item in query ) {
Console.WriteLine( "{0},\t{1},\t{2}",
item.LastName,
item.FirstName,
item.Nationality );
}
}
}

Notice that because the select clause simply returns the range variable, this whole query expression is nothing more than a sort operation. But it sure is a convenient way to sort things in C#. In this example, I sort first by Nationality in ascending order, then the second expression in the orderby clause sorts the results of each nationality group by LastName in descending order, and then each of those groups is sorted by FirstName in descending order.

At compile time, the compiler translates the first expression in the orderby clause into a call to the OrderBy standard query operator extension method. Any subsequent secondary sort expressions are translated into chained ThenBy extension method calls. If orderby is used with the descending keyword, the generated code uses OrderByDescending and ThenByDescending respectively.

Source Of Information : Apress Accelerated C Sharp 2010

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner