Im trying to create a random 6 digit numeric code that will not repeat.
I have tried using guid but that was unsuccessful.

random rnd = new random();
int num = rnd.next(000001,999999);

I would prefer not to use Random , or to have to iterate through all the previous codes to get a code.

So you want a six digit number that doesn't have repeating values in it (382945 is good, 235782 is bad). Well, one way to look at the problem is that you want a combination of the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} in a group size of six. Take a look at the Combination generation code here.

After setting up the object, you'd generate a random number from zero to NumberOfCombinations. Then use the GetCombination method to get that specific lexical combination.

Another way to do it would be to create a list of the numbers from 0 to 9. Then randomly get one of the numbers and remove it from the list. Randomly get one of the remaining, etc. until you have 6 numbers.

Thanks for your reply, it doesnt matter if it has repeating values.
It matter if it repeats the exact same number (382945 is good, 235782 is also fine)

If you simply want uniqueness, take the highest number you already have and add 1. Simple yet effective.

You said that you don't want to have to iterate through all previous codes, yet, you have to anyway to check that the number you have is unique. There are ways to increase the entropy of the distribution but the chance of hitting an existing number with RAND is quite high compared to using GUID or single digit incrementing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.