Dynamic Sort With LINQ
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.
11 Responses to Dynamic Sort With LINQ
Leave a Reply Cancel reply
Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML


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
[...] 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 [...]
God Bless You!!!
Bablo,
I hope that article was of help to you.
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
Thanks mate, that was very helpful.
Most welcome Chris.
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
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);
}
}
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 :)
How to I handle if I want the sort column to order by nulls “last”?