First of all, to use Random
, you should only create a single instance for your class and initialize it once. Otherwise you run the risk of getting the same number from them if called in a loop, since it's initialized by the system clock.
Secondly, if you want to pick five unique indexes from a list, you can simply create a list of all the indexes, shuffle them, and then pick the first five from that.
In the code below, I use Enumerable.Range(0, cardImageList.Images.Count)
to get a sequential list of cardImageList.Images.Count
numbers, starting at 0
. This is simplified syntax that could be replaced with a for
loop. Next I use the System.Linq
extension method OrderBy
to sort the index list, and I pass Random.NextDouble()
to it. This makes it order the list in a random way; basically a simple way to "shuffle" a list. After the list of indexes is shuffled, I use the Take()
extension method to take the first five items from the list:
namespace Random_Card
{
public partial class Form1 : Form
{
private Random rand = new Random();
public Form1()
{
InitializeComponent();
}
private void getCardButton_Click(object sender, EventArgs e)
{
// Get five unique random indexes
List<int> shuffledIndexes = Enumerable.Range(0, cardImageList.Images.Count)
.OrderBy(x => rand.NextDouble()).Take(5).ToList();
cardPictureBox.Image = cardImageList.Images[shuffledIndexes[0]];
cardPictureBox1.Image = cardImageList.Images[shuffledIndexes[1]];
cardPictureBox2.Image = cardImageList.Images[shuffledIndexes[2]];
cardPictureBox3.Image = cardImageList.Images[shuffledIndexes[3]];
cardPictureBox4.Image = cardImageList.Images[shuffledIndexes[4]];
}
}
}
Update: You mentioned that you didn't know how to do this in a loop, so here's an example of the "long-hand" method to do the same thing, which may make more sense.
var shuffledIndexes = new List<int>();
// Get a sequential list of integers representing the indexes
for (int i = 0; i < cardImageList.Images.Count; i++)
{
shuffledIndexes.Add(i);
}
// Shuffle the items in the index list by randomly swapping each item with another
for (int i = 0; i < cardImageList.Images.Count; i++)
{
// Pick a random item to swap with
var swapIndex = rand.Next(shuffledIndexes.Count);
// If we picked the current item, continue without doing anything
if (swapIndex == i) continue;
// Otherwise, swap the current item with the random item
var temp = shuffledIndexes[i];
shuffledIndexes[i] = shuffledIndexes[swapIndex];
shuffledIndexes[swapIndex] = temp;
}
// Assign the images from the first five shuffled indexes
cardPictureBox.Image = cardImageList.Images[shuffledIndexes[0]];
cardPictureBox1.Image = cardImageList.Images[shuffledIndexes[1]];
cardPictureBox2.Image = cardImageList.Images[shuffledIndexes[2]];
cardPictureBox3.Image = cardImageList.Images[shuffledIndexes[3]];
cardPictureBox4.Image = cardImageList.Images[shuffledIndexes[4]];