How to Generate Unique Number of 8 digits?

后端 未结 9 927
庸人自扰
庸人自扰 2020-12-30 01:39

I am using this code to generate a 8 digit unique number.

byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToUInt32(buffer, 8).ToString();
<         


        
9条回答
  •  时光说笑
    2020-12-30 02:18

    This method will generate a random string, it doesn't rely on the Random method and also is far better than the guid approch :

    public static string gen_Digits(int length)
    {
        var rndDigits = new System.Text.StringBuilder().Insert(0, "0123456789", length).ToString().ToCharArray();
        return string.Join("", rndDigits.OrderBy(o => Guid.NewGuid()).Take(length));
    }
    

    you can increase the length for less collision chance, but to have a 100% unique sequence you have to persist the old generated values and check the newly created value for uniquness.

提交回复
热议问题