Randomizing A Collection: One Time or Forever

Recently, while working on a new version of my dotNetTips Utility Dev App (free for developers), I modified it to retrieve messages that I display where I will be speaking next and more from a project I wrote in Azure. While hooking that up in my client app, I decided to create an easier way to randomly choose items from a collection that can also loop forever. So, I’ve added a new class called CollectionRandomizer<T>.

This class requires a collection when initialized. By default, it randomizes the collection and then allows retrieving items until it reaches the end of the list. To retrieve an item out of CollectionRandomizer<T>, just use the GetNext() method. When creating the class you can also set the repeat parameter to true. It will re-randomize the list when it gets to the end of the list and will continue doing this, well forever. This is what works perfectly in my app.

This is an example of how to create the type.

private CollectionRandomizer<Ad> _adRandomizer;

this._adRandomizer = new CollectionRandomizer<Ad>(ads, repeat: true);

This is how to retrieve an item out of the collection.

var ad = this._adRandomizer?.GetNext();

To check if there are items still in the collection to process, you can use the HasRemainingItems property.

This class has been fully tested, so if you need anything like this, I hope you give it a try. I’d like to thank my teammate Kristine Tran for being my second pair of eyes when writing this code.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

5 thoughts on “Randomizing A Collection: One Time or Forever

  1. If you are going to repeat from the same pool, but only re-randomize once you have exhausted values, there are statistical patterns that will emerge in the resulting data stream. If the number of repeats is high compared to the number of items, the overall sequence ill become more predictable than a true random…

  2. (This is “zames” from above. Not sure what login manner I used to get that avatar)

    The interface seems a bit odd. It’s sort of like IEnumerable, but inverted. It should be simple to convert to an IEnumerable. That way it can be used to fill an List<> or in a foreach etc.

    I’d also replace the repeat boolean with a repeat count (default 1, -1 = forever)

Leave a reply to dotNetDave Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.