Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Andrew Hopkins 17 posts 118 karma points
    Sep 30, 2019 @ 13:35
    Andrew Hopkins
    0

    OrderByDescending in version 8 with custom date field

    I have this code in Version 7 to display news items by a custom date field but when I do this in Version 8 it breaks, any ideas what I'm doing wrong? Apologies my Linq & Lambda knowledge is very poor :(

    var items = Model.Content.Site().FirstChild("news").Children("newsItems").Where(x => x.IsVisible()).OrderBy("newsDateTime descending");
    

    Version 8 - Custom date field alias: newsDate (I'm also picking the starting parent from the tree in the variable 'guid'), this works with x.CreatedDate but I really need to do this from a user-defined field.

    var guid = @Model.Value("repeaterGUID");
    var selection = Umbraco.Content(Guid.Parse(@guid.ToString()))
    .Children()
    .Where(x => x.IsVisible())
    .OrderByDescending(x => x.Model.Value("newsDate"));
    
  • Steve Megson 118 posts 688 karma points c-trib
    Sep 30, 2019 @ 14:50
    Steve Megson
    1

    I think you just need to use x.Model.Value<DateTime>("newsDate") so that OrderByDescending knows that it's sorting dates.

    Although Model.Value("newsDate") will be returning DateTimes, as far as OrderByDescending knows it could return any object. It doesn't know that they all happen to be DateTimes, and since it doesn't know how to compare object, it breaks.

  • Andrew Hopkins 17 posts 118 karma points
    Sep 30, 2019 @ 15:04
    Andrew Hopkins
    0

    Thanks, Steve really appreciate you taking the time to reply. I had tried this previously and just again now, but I still get an error, so I think it could be the version of 8 I am using (Umbraco version 8.0.2) which is the issue as the error seems unrelated to the task at hand.

  • Steve Megson 118 posts 688 karma points c-trib
    Sep 30, 2019 @ 15:37
    Steve Megson
    100

    Oops, I skipped straight to the sorting and forgot that Children is a property now. Try this:

    var selection = Umbraco.Content(Guid.Parse(@guid.ToString()))
    .Children
    .Where(x => x.IsVisible())
    .OrderByDescending(x => x.Value<DateTime>("newsDate"));
    
  • Andrew Hopkins 17 posts 118 karma points
    Sep 30, 2019 @ 15:49
    Andrew Hopkins
    0

    Perfect!! A million thanks!!

    var guid = @Model.Value("repeaterGUID");
    var selection = Umbraco.Content(Guid.Parse(@guid.ToString()))
    .Children()
    .Where(x => x.IsVisible())
    .OrderByDescending(x => x.Value("newsDate"));
    
Please Sign in or register to post replies

Write your reply to:

Draft