我從ListBox
創建另一個隨機生成器。我希望他們隨機從listBox
中挑選3件物品,然後在TextBox
上展示它。如何從列表框中選擇不重複的隨機項目
Random random = new Random();
int a = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[a];
int b = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[b];
int c = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[c];
listBox1.Select();
textBox1.Text = listBox1.Items[a] + ", " + listBox1.Items[b] + ", " + listBox1.Items[c];
該問題有時會被選中兩次。 例子:
ListBox的項目:一,二,三,四,五,六
輸出:一,六,一(選擇兩次項目「一」,這是我不希望)
謝謝。
使用enumerable.range獲取從0到list.count的整數列表 - 查找混洗算法。就像洗牌一樣。 – Derek
[生成隨機,唯一值C#]的可能的重複(https://stackoverflow.com/questions/14473321/generating-random-unique-values-c-sharp) – EpicKip