Get Sitecore Items Sorted By Created By

I am trying to get some Sitecore elements and then sort them by creation date using the latest elements.

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 get the following error:

At least one object must implement IComparable.

I am not sure how I should fix this.

+4
source share
2 answers

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

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

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

+4

, Bucket, API ContentSearch ( , , ).

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);
        }
    }
}
+3

Source: https://habr.com/ru/post/1620404/


All Articles