Inline sorting

 Posted by  Programming  Add comments  Tagged with:
Apr 142013
 

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>