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 629 posts 1016 karma points
    Dec 06, 2012 @ 16:15
    Dan Evans
    0

    Sorting a collection randomly

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

    e.g.

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

  • Jan Skovgaard 11280 posts 23678 karma points MVP 10x admin c-trib
    Dec 06, 2012 @ 20:32
    Jan Skovgaard
    0

    Hi Dan

    I think the approach should be done a bit like Rasmus is showing in this post http://our.umbraco.org/forum/developers/razor/35398-display-random-node (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.

    /Jan

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

    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();
    foreach
    (var item in items)
    {

    Ben

  • Dan Evans 629 posts 1016 karma points
    Dec 11, 2012 @ 14:35
    Dan Evans
    0

    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?

    Thanks

    Dan

  • Dan Evans 629 posts 1016 karma points
    Dec 11, 2012 @ 14:50
    Dan Evans
    2

    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
    1

    You can add an exstention method in your App_Code:

    Extensions.cs

    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:

Draft