Tuesday, October 07, 2008

Sorting a Generic List of Strings in C#

I've been looking around at how to implement a descending sort for a generic list of strings (List). After looking at several options of implementing IComparable, converters, and all sorts of other madness, it turns out the List object has a very easy way of doing this. So easy, in fact, that I'm sort of embarrassed I didn't just know it. In case there is anyone else who is in need of this simple solution, here is a short example.

List myList = new List();
myList.Add("AAAA");
myList.Add("ZZZZ");
myList.Add("MMMM");

myList.Sort();
myList.Reverse();

Painfully easy.

1 comment:

crd said...

This is the kind of functionality that makes the .NET framework so enjoyable to code with. You're right about the "painfully easy," though. Even with a line or two of code we were implemented a custom sort method.