Last week, an interesting problem came on my desk. Initially, when I was asked to sort items, I didn’t think much of it. Given a list of items, it’s fairly trivial to use LINQ and sort it by whatever property you want. What I hadn’t quite anticipated was that the user should be able to select between multiple sorting criteria.
If there was a predetermined sorting criterion, the problem would be straightforward. For instance, given a list of Fruits with a name, supplier and price, I can easily sort them by price:
static void Main(string[] args)
{
var apple = new Product() { Supplier = "Joe's Fruits", Name = "Apple", Price = 1.5 };
var apricot = new Product() { Supplier = "Jack & Co", Name = "Apricot", Price = 2.5 };
var banana = new Product() { Supplier = "Joe's Fruits", Name = "Banana", Price = 1.2 };
var peach = new Product() { Supplier = "Jack & Co", Name = "Peach", Price = 1.5 };
var pear = new Product() { Supplier = "Joe's Fruits", Name = "Pear", Price = 2 };
var originalFruits = new List<Product>() { apple, apricot, banana, peach, pear };
var sortedFruits = originalFruits
.OrderBy(fruit => fruit.Price);
foreach (var fruit in sortedFruits)
{
Console.WriteLine(string.Format("{0} from {1} has a price of {2}.",
fruit.Name,
fruit.Supplier,
fruit.Price));
}
Console.ReadLine();
}
Running this simple console application produces the following list, nicely sorted by price:

However, if we want to give the user to select how fruits should be sorted, the problem becomes a bit more complicated. We could write a switch statement, with something like “if 1 is selected, then run this sort, else run that sort, else run that other sort”, and so on. It would work, but it would also be ugly. We would be re-writing essentially the same OrderBy statement over and over again, something which reeks of code duplication. How could we avoid that, and keep our code smelling nice and fresh?
More...