Tuesday, July 17, 2007

Sorting a Generic List

Here is the code to sort objects in Generics. It is a very nice approach as client gets to decide what property in an object to sort by.


//sort the menu items by the tab order
menuItems.Sort(new Comparison(
delegate(PageDto page1, PageDto page2)
{
return Convert.ToInt32(SortOrder.Ascending) * page1.CurrentTabOrder.CompareTo(page2.CurrentTabOrder);
})
);


In this example, I have a list of menu items in a List Collection. The Sort function calls for a Comparison object which itself looks for a delegate of the sorting mechanism in which I as the client pass in. This way I determine the sort rules and then just pass that in