Pages

Saturday, August 11, 2012

C# LINQ - OrderBy clause

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

Today we'll see practical examples of using OrderBy, ThenBy clauses in LINQ. This kind of operators in LINQ are called LINQ Ordering Operators.
List<Employee> employees = GetEmployeeList();

var sortedEmployees =
    from e in employees
    orderby e.EmployeeName
    select e;
Console.WriteLine("Employees list ordered by name:");
foreach(var e in sortedEmployees)
    Console.Write(e.EmployeeName + ", ");    /*    Output:    John, Lucas, Marina, Susan, Tomas   */

We can also order our objects in opposite way simply by adding descending keyword:
var sortedEmployees =
                from e in employees
                orderby e.EmployeeName descending
                select e;
If we need to sort the employees by name and then by country they living in, we do it this way:
List<Employee> employees = GetEmployeeList();

var sortedEmployees =
        from e in employees
        orderby e.EmployeeName, e.EmployeeCountry
        select e;            
foreach(var e in sortedEmployees)
    Console.WriteLine(e.EmployeeName + " (" + e.EmployeeCountry + ")");    

/*  Output:
 * 
 *  John (USA)                
 *  Lucas (England)                
 *  Marina (Russia)                
 *  Susan (England)
 *  Tomas (USA)   
 */

No comments:

Post a Comment