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:

Tagged with:
 

11 Responses to Dynamic Sort With LINQ

  1. [...] ago I wrote a post showing how to do dynamic sort with LINQ. That approach worked well with LINQ To Objects. Today I spotted a question on the forums where [...]

  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

  5. Chris says:

    Thanks mate, that was very helpful.

  6. Deepak says:

    Most welcome Chris.

  7. dotnetter says:

    Is there already an answer on the following question:

    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

  8. Jovica Milenovic says:

    You can also use reflection:

    sortedList = (from n in createData() orderby LinqHelper.GetDynamicSortProperty(n, “PropertyName”) ascending
    select n).ToList();

    public static class LinqHelper
    {
    public static object GetDynamicSortProperty(object item, string propName)
    {
    return item == null ? null : item.GetType().GetProperty(propName).GetValue(item, null);
    }
    }

  9. Abhilash says:

    That was simply awesome!
    I stayed away from LINQ because I find it hard to debug for complex queries.
    I guess, I need to make my hands more dirty with LINQ.
    Thanks for the excellent post :)

  10. Sean B says:

    How to I handle if I want the sort column to order by nulls “last”?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>