Developer forum

Forum » Development » Randomize related products

Randomize related products

Christian Hansen Nørgaard
Reply

Is it possible to somehow randomize related products? I guess I'll have to extract the related products out into a new List which I then add some custom randomization code to but I do not know what type of object a RelatedProduct is? The below code returns nothing in the relatedproducts.

        @functions{
            public List<object> relatedproducts = new List<object>();

            public static List<T> Randomize<T>(List<T> list)
            {
                List<T> randomizedList = new List<T>();
                Random rnd = new Random();
                while (list.Count > 0)
                {
                    int index = rnd.Next(0, list.Count); //pick a random item from the master list
                    randomizedList.Add(list[index]); //place it at the end of the randomized list
                    list.RemoveAt(index);
                }
                return randomizedList;
            }
        }

        @{
            foreach (LoopItem relatedGroups in GetLoop("ProductRelatedGroups"))
            {
                foreach (LoopItem related in relatedGroups.GetLoop("Products"))
                {
                    relatedproducts.Add(related);
                }
            }

            Randomize(relatedproducts);
    }


Replies

 
Christian Hansen Nørgaard
Reply

Ah It's a LoopItem object. Also I forgot to recreate the list with var newrelatedproducts = Randomize(relatedproducts);

Now it works. :)

 

You must be logged in to post in the forum