6

How do I sort my search results using item.Fields["Name"}?

var queryable = context.GetQueryable<SearchResultItem>();
queryable  = queryable.OrderByDescending(x => x.Fields["MyDateField"]);
var results = queryable.GetResults();

It throws an error when I run it:

The method 'get_Item' is not supported. Declaring type: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]. Exception: System.InvalidOperationException: variable 'x' of type 'Sitecore.ContentSearch.SearchTypes.SearchResultItem' referenced from scope '', but it is not defined

On the other hand, this works:

queryable  = queryable.OrderByDescending(x => x.CreatedDate);
var results = queryable.GetResults();

1 Answer 1

11

You will need to define a custom model that inherits from SearchResultItem to define the field you want to sort based upon using the Content Search API. So assuming your Date field was called Podcast Date, you would define the following model:

namespace Something.Data
{
   public class PodcastDateSearchItem : SearchResultItem
   {
      [IndexField("podcast_date")]
      public DateTime PodcastDate { get; set; }
   }
}

Once you have that, your Content Search Api Query should look like this:

namespace Something.Data.Repository
{
    public class AudioRepository
    {
        public IEnumerable<Items> GetPodcastItems()
        {
            using (var context = Sitecore.ContentSearch.ContentSearchManager.CreateSearchContext(new SitecoreIndexableItem(Sitecore.Context.Item)))
            {
                var query = context.GetQueryable<PodcastDateSearchItem>();

                query = query.OrderByDescending(x => x.PodcastDate);

                var results = queryable.GetResults();
            }
        }
    }
}

You can use Luke to find out what the index field name is for your field, it's typically all lowercase and spaces are replaced with underscores.

1
  • Absolutely, if it solves your problem, up-vote and mark it the correct answer. Let me know if you have any other questions. Commented Apr 6, 2018 at 23:28

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.