Friday 7 August 2009

Sorting Lists with Comparison in .Net

The other day, I made a post about invoking methods using reflection. One of the things I wanted to do in my code was get a list of the methods in a class and then run them. However, what I didnt mention was that I wanted the methods added to my list in an order. Sorting a list is easy if you are working with a list of strings or numbers. But the list I generated was a list of type MethodInfo - something that .Sort wouldnt work with.

So, to overcome this, I did the following:
sectionNames.Sort(delegate(MethodInfo m1, MethodInfo m2) { return m1.Name.CompareTo(m2.Name); });

And out pops a sorted list of type MethodInfo. Short, but sweet and also provides a nice little example of how lists of different types can be sorted.