Copied to clipboard

Flag this post as spam?

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

  • Dan Evans 622 posts 994 karma points
    Dec 06, 2012 @ 16:15
    Dan Evans

    Sorting a collection randomly

    Is it possible to use OrderBy to sort child nodes randomly?


    foreach (var item in Model.Descendants().OrderBy("random")

  • Jan Skovgaard 11259 posts 23501 karma points MVP 8x admin c-trib
    Dec 06, 2012 @ 20:32
    Jan Skovgaard

    Hi Dan

    I think the approach should be done a bit like Rasmus is showing in this post (Just click go to solution).

    You just need to set the max value high enough to make sure all your nodes are sorted random.

    Hope this is what you're looking after.


  • Ben Norman 167 posts 275 karma points
    Dec 06, 2012 @ 21:30
    Ben Norman

    one of the suggestions was to do the following which should get you out of trouble

    var items = Model.Descendants().OrderBy(i => Guid.NewGuid()).ToList();
    (var item in items)


  • Dan Evans 622 posts 994 karma points
    Dec 11, 2012 @ 14:35
    Dan Evans

    Jan - thanks but your solution is for a single node. I need to order a collection randomly.

    Ben - this is what I need but am getting this error:

    Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

    Any ideas?



  • Dan Evans 622 posts 994 karma points
    Dec 11, 2012 @ 14:50
    Dan Evans

    Worked it out:

    foreach (var item in Model.NodeById(sourceId).Descendants().Where("NodeTypeAlias == \"APerfectCVTestimonial\"").Random(@Model.NodeById(sourceId).Descendants().Where("NodeTypeAlias == \"APerfectCVTestimonial\"").Count())){
  • Jeremy Pyne 106 posts 246 karma points MVP c-trib
    Dec 11, 2012 @ 22:52
    Jeremy Pyne

    You can add an exstention method in your App_Code:


    using System; using System.Collections.Generic; using System.Linq;

    namespace Extensions {
    public static IEnumerable Randomize(this IEnumerable source)
       Random rnd = new Random();
       return source.OrderBy((item) => rnd.Next());

    Then in your macros you can do this:

    @using Extensions
    foreach(var item inModel.Descendants().Randomize())
Please Sign in or register to post replies

Write your reply to: