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.
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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With