Pick Random String From Array

The simplest way (but slow for large lists) would be to use a resizeable container like List and remove an element after picking it. Like:

var names = new List<string> { "image1.png", "image2.png", "image3.png", "image4.png", "image5.png" };

int index = random.Next(names.Count);
var name = names[index];
names.RemoveAt(index);
return name;

When your list is empty, all values were picked.

A faster way (especially if your list is long) would be to use a shuffling algorithm on your list. You can then pop the values out one at a time. It would be faster because removing from the end of a List is generally much faster than removing from the middle. As for shuffling, you can take a look at this question for more details.

Leave a Comment