Search code examples
sitecoresitecore6

Sitecore foreach but order children by date field


I currently have webforms iterating and outputting Sitecore items based on their natural order within Sitecore.

Specs now changed to wanting a datefield against each item and that will now determine sort order by oldest first - whats the easiest method to iterate through but sort the list first by the datefield within each item?

Field name is EVENTDATE

Page was currently happy using:

Sitecore.Collections.ChildList eventItems;
eventItems = eventRange.GetChildren();

foreach (Item eventItem in eventItems) {
    timelineHolder.InnerHtml += "<h3>" + eventItem.Fields["Title"] + "</h3>";
}

Thanks for any help


Solution

  • Just add .OrderBy(ei => ei["EVENTDATE"]) in your foreach loop:

    Sitecore.Collections.ChildList eventItems;
    eventItems = eventRange.GetChildren();
    
    foreach (Item eventItem in eventItems.OrderBy(ei => ei["EVENTDATE"]))
    {
        timelineHolder.InnerHtml += "<h3>" + eventItem.Fields["Title"] + "</h3>";
    }
    

    Dates are stored as strings in Sitecore (in Sitecore 8 it's 20171012T000000Z, in Sitecore 6 it's shorter format). Ordering them alphabetically in fact sorts by dates.