After looking at Predicate<T> I thought it would be cool to take a squizz at the Comparison<T> generic delegate type and the Sort(…) method found on generic collections. Comparison<T> allows you to sort lists of items in the same way that you used to use an IComparer, the difference is that you can declare them inline with your method which means you don’t have proliferation of type definitions in your code (**).

ComparisonOfT

Look at the first commented section, here I am simply sorting by the driver’s rating. In the second commented section I am doing a slightly more complex sort by sorting by rating AND THEN by the driver’s first name. For simple sorts you’d probably do it inline with the method call versus splitting it out into its own block, but for more complex sorting I would recommend defining it and stuffing the implementation into its own couple of lines of code.

You can download the code for this demo here.

** Note that while you don’t end up creating additional types in your code, the C# compiler actually produces a method and field for each anonymous method. This is a little bit different to what I observed with earlier versions of VS2005 which produced a whole extra type.