Have you ever asked yourself what’s the fastest (or easiest) way to sort a list of item that you retrieve using SelectItems or something similar? It’s been answered before and there’s even been sample code provided before. Here are some of the ones I’ve seen:
- using IComparer
- brute-force approach
- using the “sortorder” provided by Sitecore
I think the last two is self-explanatory but the first one is something that I’ve seen before on SDN and works really well. You can see a sample code on:
This solution is a definite .NET way of doing it. I would actually say old-school but effective. It uses the Sort method and passing it a custom IComparer. Just a simple Title sort would at least be 3-5 lines of code.
Although with the new C# 2.0 syntax, you can reduce the # of lines by using anonymous methods such as:
numbers.Sort((x,y) => Int32.Parse(x).CompareTo(Int32.Parse(y)));
Now comes C# 3.0’s support for LINQ, you can now use that technique to do a one-line code…yes ONE LINE!!!
The code is:
var sortedList = (from entry in unsortedItems orderby entry.Fields[“Title”].Value ascending select entry);
where unsortedItems is an array of Items (i.e. Item) or an ItemList or any type of collection for that matter.
So how does it work? If you’ve done LINQ (or even SQL statements) before, this should be familiar but if not, it’s quite easy. The code above grabs an Item from the unsortedItems into a variable called entry. Using the entry’s Fields property and the proper field name, I sort it using either “ascending” or “descending” keyword. The “select entry” essentially completes the statement to store that same entry into the resulting variable "sortedList”.
I’ve used this technique with other field types as well and works very well. Of course, you may need to revert back to using IComparer if you have more complex comparison rules.
FYI for algorithm folks, there has been mention that the LINQ’s OrderBy sort is O(n*log(n)) compared to IEnumerable’s O(n*n) which according to some is about 5 times slower with a large sample. Here’s a link you can get a more detailed analysis of OrderBy and Sort.