How to sort Lists in C# or: IComparer rocks!

Posted by on Feb 26, 2014 in Game Development, Programming | No Comments

For a game i’m working on i needed to sort cities based on the commodities that are sold in these cities. The list should be sortable by buy/sell price, estimated profit with current player cargo and city names.

As my commodity and city classes are quite complex i feared that i would have to write a custom search class for this. As i didn’t really wanted that, i had a look around and soon found out, that C# has numerous ways of helping the user sorting his stuff. In fact, lists already have a Sort() function implemented which uses Quick Sort.

My first implementation looked something like this:

This worked great, but i wanted a more general approach which would not only let me  sort cities based on commodity prices, but virtually anything. So i had a look at IComparer which is actually exactly what i needed.
Basically you just write a custom comparer for each class you want to sort, pass that to the list’s Sort() function and you are set. Great!

And here’s how to use it:

Now i can sort my cities based on their commodities, name, size, position, citizens and how many pieces of socks each citizen owns. I just have to pass a coresponding comparer to my GetSortedCities() function!

More sorting goodness can be found in this awesome stackoverflow thread.