我想知道如何在列表框中获得8个唯一的随机数,代码到目前为止:
lbLeft.Items.Clear();
Random rnd = new Random();
int n = rnd.Next();
int x = 8;
do
{
lbL.Items.Add(rnd.Next(0, 20));
} while ((lbLeft.Items.Count != x));
Run Code Online (Sandbox Code Playgroud)
它用8个随机数填充列表框,但我需要它们是唯一的.
任何帮助将不胜感激,
HashSet<int> uniques = new HashSet<int>();
Random random = new Random();
while(uniques.Count!= 8)
{
uniques.Add(random.Next(0,20)); //terrible upper bound
}
Run Code Online (Sandbox Code Playgroud)
这Set将保证重复项不能包含在其中.