Randomize a page data collection in EPiServer

Here's a neat little function that will randomize the order of a PageDataCollection. The random order will be changed on each and every call (using a different random seed based on current date and time in ticks). If you're using the result in a paged list you might want to consider tweaking the code somewhat, either caching the list or by caching the seed and send it into the function instead of using the DateTime.Now.Ticks on every call.
public static PageDataCollection Shuffle(PageDataCollection originalCollection) {
      
// Create randomizer
Random rnd = new Random((int)DateTime.Now.Ticks);

// Create an array of PageData from the PageDataCollection sent to this function
PageData[] pages = new PageData[originalCollection.Count];
originalCollection.CopyTo(pages, 0);

// Create a byte array of the same length and fill with random values
byte[] randomBytes = new byte[pages.Length];
rnd.NextBytes(randomBytes);

// Sort array of PageData based on random values in the byte array
Array.Sort(randomBytes, pages);

// Return the randomly sorted PageDataCollection
return new PageDataCollection(pages);
}

Related posts:

Comments

comments powered by Disqus