LINQ Ordering Operators

LINQ comes packed with few useful ordering operators. These are:
OrderBy, ThenBy, OrderByDescending and ThenByDescending. I will
walkthrough these operators using an example of cities. Here is the
code for City class.

public class City
{
    public string Name { get; set; }
    public string Country { get; set; }
}

Below is the intitializer for cities collection.

List<City> cities =
    new List<City>
    {
        new City{ Name = "Sydney", Country = "Australia" },
        new City{ Name = "New York", Country = "USA" },
        new City{ Name = "Paris", Country = "France" },
        new City{ Name = "Milan", Country = "Spain" },
        new City{ Name = "Melbourne", Country = "Australia" },
        new City{ Name = "Auckland", Country = "New Zealand" },
        new City{ Name = "Tokyo", Country = "Japan" },
        new City{ Name = "New Delhi", Country = "India" },
        new City{ Name = "Hobart", Country = "Australia" }
    };

 

I will now walk you through ordering operators. First one we will
look at is the OrderBy operator. OrderBy as the name implies orders the
collection with a specified field in ascending order. To order our
collection by country we can use the following code.

var result =
    from c in cities
    orderby c.Country
    select c;

Using the loop below I can see that my collection has been ordered by country.

foreach (var item in result)
{
    Console.WriteLine(
        string.Format("Name: {0}t Country: {1}", item.Name, item.Country));
}

And here is the output. 

image8 LINQ Ordering Operators

ThenBy operator can be used to order an already ordered collection
using another criteria. For example we can use it to order our list by
Country and then by Name.

var result =
    cities
    .OrderBy(c => c.Country)
    .ThenBy(c => c.Name);

I can also use ThenBy explicitly in my OrderBy like this.

var result =
    from c in cities
    orderby c.Country, c.Name
    select c;

OrderByDescending orders the collection in descending manner. This can be accomplishes by simply using the descending keyword.

var result =
    from c in cities
    orderby c.Country descending
    select c;

ThenByDescending orders an already ordered collection using another criteria but this time in descending manner.

Explicit use of ThenByDescending:

var result =
    cities
    .OrderBy(c => c.Country)
    .ThenByDescending(c => c.Name);

Implicit use of ThenByDescending:

var result =
    from c in cities
    orderby c.Country, c.Name descending
    select c;

By using ThenByDescending operator explicitly or implicitly we get the same output. 

image41 LINQ Ordering Operators

Originally Posted at http://www.deepakkapoor.net/blog/2008/06/23/linq-ordering-operators/

GD Star Rating
loading...
GD Star Rating
loading...
LINQ Ordering Operators, 3.0 out of 5 based on 1 rating
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply