Article Publish Date is a field of type Datetime

List<Item> articles = GetArticles();

articles = articles.OrderByDescending(x => x.Fields[Constants.Templates.Article.Fields.ArticlePublishDate]).ToList();

The above line of code throws an error:

At least one object must implement IComparable.

How can this be resolved.


Mahendra's answer will work, but it is also possible to cast your field to a Sitecore.Data.Fields.DateField and retrieve the DateTime property, which will actually properly parse the field value and return a sortable DateTime value. I would implement it like this:

List<Item> articles = GetArticles();

articles = articles.OrderByDescending(x => ((Sitecore.Data.Fields.DateField)x.Fields[Constants.Templates.Article.Fields.ArticlePublishDate]).DateTime).ToList();
  • 2
    This is the more reliable (albeit likely slower) way to solve the original question. – Dan Sinclair Sep 19 '19 at 14:02
  • 2
    @DanSinclair Definitely slower, but not noticeable unless you're running on a very large number of articles. But if you are doing that, your performance problem would come from fetching a large number of articles from the Sitecore database, not from parsing the datetime. – Matthew FitzGerald-Chamberlain Sep 19 '19 at 14:34
  • @MatthewFitzGerald-Chamberlain If the date field is empty. How will it be in the order. Will it throw an error. – Qwerty Sep 25 '19 at 7:08
  • 1
    @Qwerty It would be parsed as DateTime.MinValue so it would appear last in the list, same as in your's and Mahendra's – Matthew FitzGerald-Chamberlain Sep 25 '19 at 13:26

You are trying to sort by field not value, try below by removing Fields-

List<Item> articles = GetArticles();

articles = articles.OrderByDescending(x => x[Constants.Templates.Article.Fields.ArticlePublishDate]).ToList();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.