Unique 4 digit random number in C#

2019-06-15 01:41发布

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

Code for generating random number

//Generate RandomNo
public int GenerateRandomNo()
{
    int _min = 0000;
    int _max = 9999;
    Random _rdm = new Random();
    return _rdm.Next(_min, _max);
}

The problem is I have received a random no with value 241 which is not a 4 digit number. Is there any problems with the code?

标签: c# random
9条回答
Summer. ? 凉城
2楼-- · 2019-06-15 01:58

You can consider something like this.

int length = 4;
int number = 50;
string asString = number.ToString("D" + length);

The above code gives the result 0050.

Similarly you can try converting to string and verify.

查看更多
甜甜的少女心
3楼-- · 2019-06-15 02:01
//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

查看更多
再贱就再见
4楼-- · 2019-06-15 02:04

0 is the same as 0000.

241 is the same as 0241.

You could format the integer to a string with a leading zero.

查看更多
一纸荒年 Trace。
5楼-- · 2019-06-15 02:08
Random generator = new Random();
string number = generator.Next(1, 10000).ToString("D4");
查看更多
姐就是有狂的资本
6楼-- · 2019-06-15 02:09

use: int _min = 1000;

or use leading 0 in case if you want 0241

查看更多
Rolldiameter
7楼-- · 2019-06-15 02:14

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);
查看更多
登录 后发表回答