Unique, Random Selections from a List
VB version here.
This is pretty simple stuff but it's come up more than once so I thought I'd post it. If you want to randomly select objects from a list where each object can only be chosen once you can use a collection and a Random object to select indexes into that collection. Below is an example using an ArrayList and the numbers 1 to 10. The objects could be anything though, not just numbers. In .NET 2.0 you'd more likely use a Generic.List<T> rather than an ArrayList.
Code:
ArrayList list = new ArrayList();
for (int i = 1; (i <= 10); i++)
{
// Add the numbers to the collection.
list.Add(i);
}
Random rand = new Random();
int index;
object item;
// Display the items in random order.
while ((list.Count > 0))
{
// Choose a random index.
index = rand.Next(0, list.Count);
// Get the item at that index.
item = list[index];
// Remove the item so that it cannot be chosen again.
list.RemoveAt(index);
// Display the item.
MessageBox.Show(item.ToString());
}