Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Sitecore Items Sorted By Creation Date

I am trying to get some Sitecore items and then sort them by their creation date with newest items first.

I have the following code (snippet):

itemID = Constants.BucketIds.NEWS;
Item pressItem = context.GetItem(itemID);
var pressChildItems = context
    .SelectItems("/sitecore/content" + pressItem.Paths.ContentPath + "/*")
    .OrderByDescending(x => x.Fields[Sitecore.FieldIDs.Created]);
foreach (Item childItem in pressChildItems)
{
    // DO SOMETHING
}

I am getting the following error back:

At least one object must implement IComparable.

I am not sure how I am supposed to fix this.

like image 935
eat-sleep-code Avatar asked Mar 13 '23 21:03

eat-sleep-code


2 Answers

Do not order by Field, sort by its value. Remove .Fields from your line:

var pressChildItems = context
    .SelectItems("/sitecore/content" + pressItem.Paths.ContentPath + "/*")
    .OrderByDescending(x => x[Sitecore.FieldIDs.Created]);

Dates are stored as yyyyMMddHHmmss... strings, so sorting by value as string will give you exactly the same effect as getting date value from field and ordering using the date.

like image 74
Marek Musielak Avatar answered Mar 17 '23 23:03

Marek Musielak


Since it looks like you have your items in a Bucket, you should really use the ContentSearch API (and limit the results if you are using them on the front-end since a bucket could potentially contain thousands of items).

using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.Data.Items;

List<Item> ResultsItems = new List<Item>();
SitecoreIndexableItem bucket = Context.Database.GetItem(Constants.BucketIds.NEWS);

using (var searchcontext = ContentSearchManager.GetIndex(bucket).CreateSearchContext())
{
    IQueryable<SearchResultItem> searchQuery =
        searchcontext.GetQueryable<SearchResultItem>()
                                        .OrderByDescending(x => x.CreatedDate)
                                        .Take(10);
    SearchResults<SearchResultItem> results = searchQuery.GetResults();

    // fetch the Sitecore Items if you do not want to work with the SearchResultItem
    foreach (var hit in results.Hits)
    {
        Item item = hit.Document.GetItem();
        if (item != null)
        {
            ResultsItems.Add(item);
        }
    }
}
like image 34
jammykam Avatar answered Mar 17 '23 21:03

jammykam