Inline Sorting

Sort is something that is almost mandatory when dealing with user-facing data. Everybody is so used to have items sorted that unsorted list really sticks out.

Assuming that we have list named myList, sorting is really easy to implement. Just call myList.Sort(). This method will search for IComparable interface (somewhat simplified view) and use it to compare elements. But what if we want order other than one defined in IComparable? And what can be done if there is no way to implement such interface (e.g. no source code for class)?

You can count on our friend delegate and Sort overload. Assuming that we want to do sort according to property DisplayName, code is:

drivers.Sort(
delegate(MyClass item1, MyClass item2) {
return string.Compare(item1.DisplayName, item2.DisplayName);
});

Yes, I know that code is old fashioned and that Linq is sooooo much better. However, this code will work on .NET Framework 2.0. And it doesn't look that bad. :)

Leave a Reply

Your email address will not be published. Required fields are marked *