Generating random, unique values C#

前端 未结 17 1368
佛祖请我去吃肉
佛祖请我去吃肉 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 15:09

    Same as @Habib's answer, but as a function:

    List randomList = new List();
    int UniqueRandomInt(int min, int max)
    {
        var rand = new Random();
        int myNumber;
        do
        {
           myNumber = rand.Next(min, max);
        } while (randomList.Contains(myNumber));
        return myNumber;
    }
    

    If randomList is a class property, UniqueRandomInt will return unique integers in the context of the same instance of that class. If you want it to be unique globally, you will need to make randomList static.

提交回复
热议问题