1

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.

2 Answers 2

2

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();
4
  • 2
    This is the more reliable (albeit likely slower) way to solve the original question. Sep 19, 2019 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. Sep 19, 2019 at 14:34
  • @MatthewFitzGerald-Chamberlain If the date field is empty. How will it be in the order. Will it throw an error.
    – sukesh
    Sep 25, 2019 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 Sep 25, 2019 at 13:26
2

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 and acknowledge you have read our privacy policy.

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