Copied to clipboard

Flag this post as spam?

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


  • JoskerVemeulen 55 posts 227 karma points
    May 10, 2019 @ 11:25
    JoskerVemeulen
    0

    Get single random item

    Hi,

    var ceremonie = Model.Root().DescendantsOrSelfOfType("ceremonie").Single();
    

    This returns a single item. Perfect. But how do i get a random single item in v8?

    Thanks!

  • Marc-André 51 posts 233 karma points
    May 10, 2019 @ 14:40
    Marc-André
    0

    Hi!

    The way I make it work was like this :

    @{
        var ceremonie = Model.Root().DescendantsOrSelfOfType("ceremonie");
        foreach (var item in ceremonie.OrderBy(x => Guid.NewGuid()).Take(1))
        {
            YOUR CODE HERE
        }
    }
    
  • JoskerVemeulen 55 posts 227 karma points
    May 12, 2019 @ 09:23
    JoskerVemeulen
    0

    This is my working solution:

     //show random ceremonie
        //get ceremonieList
        var ceremoniesList = Model.Root().DescendantsOfType("ceremonie1");
        //radomize and pick one
        var randomCeremonie = ceremoniesList.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
        //check if exist
        if(randomCeremonie != null) { 
            //pass item to ceremoniecard partial view
            @Html.Partial("~/Views/Partials/CeremonieCard.cshtml", randomCeremonie)
        }
    
  • Søren Gregersen 316 posts 1269 karma points MVP c-trib
    May 12, 2019 @ 14:24
    Søren Gregersen
    0

    Just beware of the performance of this solution. In ordrer to do the DescendantsOfType(...) all published items are evaluated. The more content you publish, the more work is being done.

    If you can, you should definetly use examine to find your “ceremonial”s.

Please Sign in or register to post replies

Write your reply to:

Draft