Copied to clipboard

Flag this post as spam?

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


  • Claushingebjerg 939 posts 2574 karma points
    Jun 22, 2017 @ 13:02
    Claushingebjerg
    0

    Getting random items

    I need to pull x random items from nested content. If i were to do it on nodes i would do:

    @foreach(var t in Umbraco.Content(1056).Children().Random(2))
    {
      <p>@t.Name</p>
    }
    

    Which works fine. In nested content context i tried doing:

    @{
        var items = Model.GetPropertyValue<IEnumerable<IPublishedContent>>("sponsorer");
        foreach(var item in items.Random(2)) {
        <p>@item.GetPropertyValue("name")</p>
        }
    }
    

    but them i get an error "CS1061: 'System.Collections.Generic.IEnumerable

  • Alex Skrypnyk 6175 posts 24186 karma points MVP 8x admin c-trib
    Jun 22, 2017 @ 15:21
    Alex Skrypnyk
    2

    Hi Claushingebjerg

    This code should work for you:

    foreach(var item in items.OrderBy(n => Guid.NewGuid()).Take(2)) 
    

    Hope it will help.

    Alex

  • Yakov Lebski 591 posts 2347 karma points
    Jun 22, 2017 @ 15:56
    Yakov Lebski
    102

    you can use this one

    items.RandomOrder();
    
  • Alex Skrypnyk 6175 posts 24186 karma points MVP 8x admin c-trib
    Jun 22, 2017 @ 16:31
    Alex Skrypnyk
    0

    Exactly, thanks Yakov, it's definitely the best method.

Please Sign in or register to post replies

Write your reply to:

Draft