Home / Programming / Blog article: Dynamic Sort With LINQ

| RSS

Dynamic Sort With LINQ

August 4th, 2008 | 5 Comments | Posted in Programming

In this post I will show you how to perform dynamic sorting with LINQ. I will work with a simple collection of City class. City class is defined below.

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

The collection is initialised using this code

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" }
            };

A typical example of applying a sort will be to write such a query.

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

Here we are sorting the collection on country. Note that this is static in nature.

Code above as you can see can only sort by country. If I wanted to sort by city name then I’d be writing another query and maybe use a conditional construct such as if or switch and write a method which takes in a parameter. While this will work, it is not the best way to do it.

LINQ gives us the ability to make our code dynamic. I can provide sort functionality for my query by writing a method which takes in a Func<TElement, TKey> delegate. This delegate is used by the OrderBy extension method. This is how I can write my method.

public static void Sort<TKey>(List<City> cities, Func<City, TKey> selector)
{
    var sortedCollection =
        from c in cities
        orderby selector(c)
        select c;

    foreach (var item in sortedCollection)
    {
        Console.WriteLine(item.Name);
    }

}

This method can be called like this by passing in the cities collection which has been initialised earlier.

Sort(cities, c => c.Name);

I can also sort by country without changing my query. To sort by country I just need to call my sort method like this.

Sort(cities, c => c.Country);

LINQ is very powerful when you start using it on daily bases. It would not be very useful if everything was static. In this post I showed you how you can make your sorting code dynamic. Stay tuned for more LINQ goodness.

kick it on DotNetKicks.com

Technorati Tags:

Leave a Reply 21605 views, 2 so far today |
Tags: ,
Follow Discussion

5 Responses to “Dynamic Sort With LINQ”

  1. LINQ Master Says:

    Good article. If you want to randomly sort the array, you can try:
    http://blog.linqexchange.com/post/2008/07/How-to-Generate-a-Random-Sequence-with-LINQ.aspx

  2. Bablo Says:

    God Bless You!!!

  3. Deepak Says:

    Bablo,

    I hope that article was of help to you.

  4. Tos Says:

    Hello,

    Great article!! I’m glad I found this…

    Now I just would like to know how to modify your Sort() function to obtain something like this dynamically (sorting multiple members, ascending or descending):

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

    Thank you so much! Cheers

Trackbacks

  1. Dynamic Sort With LINQ To SQL | One .Net Way  

Leave a Reply





Switch to our mobile site