Pedro Pedro - 3 months ago 26
C# Question

Never repeat some name

I am using c# winforms. When I click a button the program shows 2 words from the list, but sometimes the words repeat. How I do to don't let the words repeat

This is the code

private void button1_Click(object sender, EventArgs e)
{
var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
var wordsInRandomOrder = words.OrderBy(i => Guid.NewGuid());

foreach (var word in wordsInRandomOrder)
{
textBox1.Text = word;
break;
}

foreach (var word in wordsInRandomOrder)
{
textBox1.Text = textBox1.Text + " " + word;
break;
}
}

mjb mjb
Answer

Option 1:

private void button1_Click(object sender, EventArgs e)
{
    var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
    var wordsInRandomOrder = words.OrderBy(i => Guid.NewGuid()).ToList();

    //textBox1.Text = words[0] + " " + words[1]; << wrong
    textBox1.Text = wordsInRandomOrder[0] + " " + wordsInRandomOrder[1];
}

Option 2:

var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
Random rd = new Random();

int firstIndex = rd.Next(0, words.Length);
int secondIndex = rd.Next(0, words.Length);

while (secondIndex == firstIndex)
{
    secondIndex = rd.Next(0, words.Length);
}

textBox1.Text = words[firstIndex] + " " + words[secondIndex];