Copied to clipboard

Flag this post as spam?

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


  • mizzle 90 posts 325 karma points
    Feb 18, 2020 @ 21:09
    mizzle
    0

    Select Random Nodes that Share Categories chosen by Multinode Treepicker

    I have nodes that can be categorized via a multinode treepicker. When on a page that has selected categories, I want to display three items of "related content" randomly.

    So for example if a Meal page has selected "Lunch" and "Snacks" as categories I want the random display to choose a list of three other meals that ALSO have selected "Lunch" OR "Snacks".

    The best way I can think of doing this is to make a list of the multinode treepicker items:

     List<IPublishedContent> catList = currentPage.Value<IEnumerable<IPublishedContent>>("categories").ToList();
    

    and then pull one random node ID from that list, which will then be matched against the full list of All Food and displayed, again, randomly. However, I can't figure out how to randomly pull a node ID from the list.

    I'd be grateful if anyone could tell me the best way of going about this.

    Using Umbraco version 8.5.2.

  • Adam Werner 21 posts 202 karma points MVP 2x c-trib
    Feb 19, 2020 @ 02:11
    Adam Werner
    100

    I think you could generate a random number using the count from your list. Then, use that generated number as an index to obtain the random item in the list.

    Random random = new Random();
    int index = random.Next(catList.Count);
    IPublishedContent randomMealPage = catList[index];
    

    I would have liked to have tried it locally in a setup, but I haven't had the opportunity. Please let me know if it works out for you.

  • mizzle 90 posts 325 karma points
    Feb 19, 2020 @ 16:42
    mizzle
    0

    Looks like it works! Thank you!

Please Sign in or register to post replies

Write your reply to:

Draft