我正在使用c#winforms。当我单击按钮时,程序会显示列表中的2个单词,但有时单词会重复。我怎么做不要让重复的话
这是代码
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;
}
}
答案 0 :(得分:1)
选项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 = wordsInRandomOrder[0] + " " + wordsInRandomOrder[1];
}
选项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];
答案 1 :(得分:0)
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];
答案 2 :(得分:0)
不使用Guid
的类似方法:
private void button1_Click(object sender, EventArgs e)
{
Random r = new Random();
var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
var wordsInRandomOrder = words.OrderBy(i => r.Next()).ToList();
textBox1.Text = String.Join(" ", wordsInRandomOrder.Take(2));
}
使用此appraoch甚至如果,随机发生器两次生成相同的数字(这是相当不可能的),您可以从列表中选择另一个单词,因为它们只是按顺序排序。如果两个商品具有相同的订单价值,则可以任意订购,但同一商品不会被使用两次。
答案 3 :(得分:0)
如果 realllllly 希望保留您正在使用的代码,请在第二个foreach
中执行以下操作:
foreach (var word in wordsInRandomOrder)
{
if(word != textBox1.Text)
{
textBox1.Text = textBox1.Text + " " + word;
break;
}
}
但是更好的选择就像juharr写的那样:
textBox1.Text = string.Join(" ", wordsInRandomOrder.Take(2));
如果你想要循环的路线,加入可能会更好
两个" foreach
es"你喜欢这样:
foreach (string word in wordsInRandomOrder)
{
if(textBox1.Text = "")
{
textBox1.Text = word;
}
else
{
if(textBox1.Text != word)
{
textBox1.Text = textBox1.Text + " " + word;
break;
}
}
}