user5284778 user5284778 - 7 months ago 63
C# Question

How to generate 6-digit unique numbers in C# or SQL Server?

I want to generate 6-digit unique random numbers for my Users table. This unique code is different from table primary key. It should not be sequential and must be in 6-digit format. I have to ignore numbers like 111111, 222222, ...

I can use the Random() class in C# to generate it but the uniqueness is the key.

Is there any solution to do it in C# (or in SQL Server)?


You can try this

    private static string GeneratenewRandom()
        Random generator = new Random();
        String r = generator.Next(0, 1000000).ToString("D6");
        if (r.Distinct().Count() == 1)
        return r;