Generating random numbers without repeating.C#

前端 未结 11 1870
臣服心动
臣服心动 2020-12-01 17:53

Hi everyone I am trying to generate 6 different numbers on the same line in c# but the problem that i face is some of the numbers are repeating on the same line.Here is my c

11条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 18:02

    Instead of using a List, you should use an HashSet. The HashSet<> prohibites multiple identical values. And the Add method returns a bool that indicates if the element was added to the list, Please find the example code below.

    public static IEnumerable GetRandomNumbers(int count)
    {
    HashSet randomNumbers = new HashSet();
    
    for (int i = 0; i < count; i++) 
        while (!randomNumbers.Add(random.Next()));
    
    return randomNumbers;
    }
    

提交回复
热议问题