Generating random, unique values C#

前端 未结 17 1370
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:26

I\'ve searched for a while and been struggling to find this, I\'m trying to generate several random, unique numbers is C#. I\'m using System.Random, and I\'m us

17条回答
  •  礼貌的吻别
    2020-11-22 14:51

    I'm calling NewNumber() regularly, but the problem is I often get repeated numbers.

    Random.Next doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of int and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:

    public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());
                                    // Since similar code is done in default constructor internally
    public List randomList = new List();
    int MyNumber = 0;
    private void NewNumber()
    {
        MyNumber = a.Next(0, 10);
        if (!randomList.Contains(MyNumber))
            randomList.Add(MyNumber);
    }
    

提交回复
热议问题