Unique 4 digit random number in C#

前端 未结 11 1908
失恋的感觉
失恋的感觉 2021-01-01 13:19

I want to generate an unique 4 digit random number. This is the below code what I have tried:

Code for generating random number

//Ge         


        
相关标签:
11条回答
  • 2021-01-01 13:43

    Expanding on the answer from brij but with 0000 to 9999 rather than 1000 to 9999

    string formatting = "0000"; //Will pad out to four digits if under 1000   
    int _min = 0;
    int _max = 9999;
    Random randomNumber = new Random();
    var randomNumberString = randomNumber.Next(_min, _max).ToString(formatting);
    

    or if you want to minimalize lines:

    Random randomNumber = new Random();
    var randomNumberString = randomNumber.Next(0, 9999).ToString("0000");
    
    0 讨论(0)
  • 2021-01-01 13:44

    Use this code instead:

    private Random _random = new Random();
    
    public string GenerateRandomNo()
    {
        return _random.Next(0, 9999).ToString("D4");
    }
    
    0 讨论(0)
  • 2021-01-01 13:48

    I suggest to create new list and check if this list contains any of number

    var IdList = new List<int>();
    do
    {
        billId = random.Next(1, 9000);
    } while (IdList.Contains(billId));
    IdList.Add(billId);
    
    0 讨论(0)
  • 2021-01-01 13:51
    //Generate RandomNo
    public int GenerateRandomNo()
    {
        int _min = 1000;
        int _max = 9999;
        Random _rdm = new Random();
        return _rdm.Next(_min, _max);
    }
    

    you need a 4 digit code, start with 1000

    0 讨论(0)
  • 2021-01-01 13:53

    use: int _min = 1000;

    or use leading 0 in case if you want 0241

    0 讨论(0)
  • 2021-01-01 13:54
    int NoDigits = 4;
    Random rnd = new Random();
    textBox2.Text = rnd.Next((int)Math.Pow(10, (NoDigits - 1)), (int)Math.Pow(10, NoDigits) -1).ToString();
    
    0 讨论(0)
提交回复
热议问题