Tuesday 9 September 2008

Sorting a Generic List in C#

Using Sort algorithm was pretty tedious for asp.net versions prior to 2.0, and also in ASP3.0. But ASP.Net 2.0 onwards we have a very innovative feature of using delegates and sorting out the records in a generic list based on any property of the object in that list.


The following is the code sample for the same.





List SectionsList = SectionsListDataSourceObject;

SectionsList.Sort(

delegate(dataType dt1, dataType dt2)

{

return dt1.SortField.CompareTo(dt2.SortField);

});



You can use all types of fields to sort ranging from string, integer to dates, and you dont have to override any functionality. If you want to sort the records in descending order just reverse the pattern in the return statement. So that would be

return dt2.SortField.CompareTo(dt1.SortField);



Hope this saves someone quite a lot of frustration!