Dynamic sorting using LINQ. 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 this is static in nature.Code above can only sort by country. If we want to sort by city name then we have to write 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. we can provide sort functionality for the query by writing a method which takes in a Func<TElement, TKey> delegate. This delegate is used by the OrderBy extension 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 by passing in the cities collection which has been initialised earlier.
Sort(cities, c => c.Name);
we can also sort by country without changing my query. To sort by country we just need to call my sort method like this.
Sort(cities, c => c.Country);