How to Reorder / Sort a List

One of the great features WordPress offers is the ability to view search terms that people follow to get to your blog. I noticed that someone arriving here was looking for information on how to reorder a list in C# based on number.

While I don’t completely understand what they were driving at, I do think I’m able to assist with general list sorting.

Luckily, the .Net generic List class has a Sort() method. This method doesn’t know how to sort your lists though — granted there is a default sort, but I’m sure you’d rather do it yourself.

How do you sort your lists then? Well, you can create a class that implements ICompare and pass that in as a parameter. Easy.

Wait, no. That’s probably not the best way to get this done. The issue with that is it requires you to write more code than you may have to.

If you just want to order something alphabetically or numerically, then there’s a better way. LINQ.

// Imagine we have a List of objects called myList that
// needs to be sorted.
var sorted = myList
                 .OrderBy(listItem => listItem.ProductID)
                 .ToList();

Well, now SortedList contains a list that has been sorted in increasing order based on the ProductID. This will also work with strings.

There may be times when you want to build a custom comparer — such as sorting enum values, or when your values need to be sorted in increasing, decreasing, or alphabetical order.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s