Saturday, December 8, 2007

Sorting a Generic List of custom type objects in a one-liner - C#

Do I love the new features in C# 3.0!! Here is a sample. Imagine the days of implementing an IComparable or an IComparer on your custom type so they become 'sortable'. Compare that with the one-liner below :)

(Assume there is a class called opportunity that has a property called Properties, which returns a value type based on a column name and that there exist methods to give what column the user clicked on and what order did he want)

List = GetOpportunityList();
int ascending = GetOrder(); // This method will return 1 if ascending and -1 if
// descending
string columnName = GetSortedColumn(); // Get the name of the column to be sorted

// One-liner sort
opportunities.Sort((a, b) => ascending * ((IComparable)a.Properties [columnName] ).CompareTo(b.Properties[columnName]));

Isnt this real simple? Now, the additional benefit that we get out of this is the ability to pass in local variables (ascending and columnName in this case) into the lambda expression and thereby the comparison, which would have never been possible if I used the "implementing IComparable or IComparer" route.

Happy Linqing!!

No comments: