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.