Order of Sitecore Items utilising Sort Order and Created Date

A few times the ordering of objects when retrieving from Sitecore have caught me out. In a nutshell, the Sort Order field on an Item helps determines how Items are ordered, or an ordering “strategy” can be applied on the Item’s Parent to determine how the Items are sorted.

This is great, however it appears to be a little hit & miss as to whether the field will get populated if it is not understood what is happening. By default, if there is no sorting strategy specified by the Parent (by the Subitem Sorting field) then inserting an Item will leave the Sort Order field blank unless you rearrange the ordering of the items or change the Parent’s Subitem Sorting field (at which point you will see the Sort Order field populate by Sitecore). However, what if you copy, clone or move an item from another position in the tree? What if the Content Editor actually removes the Sort Order value from the field? You will end up in a position where some items have the Sort Order set and others do not (the field will be blank).

Also, if you are pulling items out of an Index (Lucene or Solr), the order of the results may not be the same as the order that they are in Sitecore. Thankfully this can be handled easily with a bit of code 🙂

As the Sort Order in Sitecore is a string field, you cannot simply perform an OrderBy() on the field as the ordering will be based on string ordering, not numeric ordering. Your results will be different.

This can cause some issues when querying items and you want to maintain the order that they appear in the CMS. The below code shows how I deal with that. Basically, I have a function delegate which handles the conversion form a string Sort Order to an integer value – if Sort Order is empty then it’s value will be 0.

private static Func<Item, int> GetSortOrderValue(List<Item> i)
 return x => string.IsNullOrEmpty(i[0][Sitecore.FieldIDs.Sortorder]) ? 0 : int.Parse(i[0][Sitecore.FieldIDs.Sortorder]);

Now we can utilise the above in a Linq statement so that we can order by Sort Order, and then order by Create Date (to cater for Items that have the same Sort Order)

private List<Item> OrderItems(List<Item> i)
    i = i.OrderBy(GetSortOrderValue(i)).ThenBy(y => y.Statistics.Created).ToList();
    return i;

Hope this makes sense 🙂