Copied to clipboard

Flag this post as spam?

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


  • Denis 47 posts 68 karma points
    Feb 25, 2014 @ 09:59
    Denis
    0

    9 Random items

    Hello, please i need help ...

    I have about 50 items in Model.Children, and i want to get 9 random items that will show to homepage.

    Every time when homepage is reloaded, i need to show different items,

    Please, how can i do that ?

  • Ismail Mayat 4331 posts 9336 karma points MVP 2x admin c-trib
    Feb 25, 2014 @ 10:11
    Ismail Mayat
    0

    Denis,

    Some code not fully tested apart from the shuffle method.

    var nodes = Model.Children.ToList();
    
    var random = nodes.Shuffle().Take(9);
    
        public static void Shuffle<T>(this IList<T> list)
        {
            var provider = new RNGCryptoServiceProvider();
            int n = list.Count;
            while (n > 1)
            {
                var box = new byte[1];
                do provider.GetBytes(box);
                while (!(box[0] < n * (Byte.MaxValue / n)));
                int k = (box[0] % n);
                n--;
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    
  • Denis 47 posts 68 karma points
    Feb 25, 2014 @ 10:57
    Denis
    0

    i have try but with problems ...

    Extension method must be defined in a non-generic static class,

    and if i dont use @using System.Collections; i have error Using the generic type 'System.Collections.Generic.IList' requires 1 type arguments

    @using System.Collections; @functions{

    public static void Shuffle(this IList list)
    {
        var provider = new RNGCryptoServiceProvider();
        int n = list.Count;
        while (n > 1)
        {
            var box = new byte[1];
            do provider.GetBytes(box);
            while (!(box[0] < n * (Byte.MaxValue / n)));
            int k = (box[0] % n);
            n--;
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }   
    

    }

  • Ismail Mayat 4331 posts 9336 karma points MVP 2x admin c-trib
    Feb 25, 2014 @ 11:18
    Ismail Mayat
    0

    denis,

    you can either create static class and put the method in there or update the metho signature and get rid of this keyword they call it like Shuffle(yourlist)

    Regards

    Ismail

  • Denis 47 posts 68 karma points
    Feb 25, 2014 @ 12:04
    Denis
    0

    Thank You, i will try ...

Please Sign in or register to post replies

Write your reply to:

Draft