Click here to Skip to main content
15,906,455 members
Please Sign up or sign in to vote.
2.78/5 (3 votes)
See more:
Hii,
I want to generate N no of 6 digit unique string(alpha numeric) i have tried below method but getting so many duplicates value please anyone can help me ????

What I have tried:

C#
public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[1];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetNonZeroBytes(data);
                data = new byte[maxSize];
                crypto.GetNonZeroBytes(data);
            }
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }

On Button Click ----
   for (int i = 0; i < LEN; i++)
             {
                
                 dt_Output.Rows.Add(GetUniqueKey(6));

                
             }

             System.Data.DataSet ds = new System.Data.DataSet();
             ds.Tables.Add(dt_Output);
Posted
Updated 10-Aug-16 7:34am
v2
Comments
BillWoodruff 10-Aug-16 10:28am    
Assuming you got this code from the CodeProject article by Aital Al Amin: when you post code that's not "original," it's a good idea to give a link to where it came from. Nothing "wrong" with re-using code, but it may help us respond to your question if we can compare your code to its source.

Couldn't you use Int32 or Int64 for the id code for the rows in the database ?

What led you to decide to use the RNGCryptoServiceProvider here: why wouldn't random numbers work for you ?

There are two ways to generate guaranteed unique keys:
1) Incrementally, so that key(N + 1) is a fixed amount greater than key(N) - usually one.
2) By reviewing all the currently generated values and checking that you didn't repeat.

The first option entails maintaining a (normally thread safe) "next value" counter and incrementing it immediately it is used.
The second means keeping a list of "issued" numbers and checking each time you try to allocate a new one to make sure it doesn't exist yet.

Random numbers are not guaranteed to be unique - even GUIDs aren't, it's just that the phase space from which they are drawn is so huge as to make it phenomenally unlikely that you would repeat it within a normal lifetime.
 
Share this answer
 
Comments
Member 10947681 11-Aug-16 0:05am    
Thanks for your answer could u provide me sample code for
2)By reviewing all the currently generated values and checking that you didn't repeat.
OriginalGriff 11-Aug-16 3:55am    
Try having a look at a Dictionary - it uses a hash table internally so lookups are pretty fast, and it's Generic which makes your code cleaner.
It may be worth you also looking at a StringDictionary - it's optimised for string keys so it could be a better choice if your list is going to get really big.
The MSDN documentation for the two classes includes examples.
BillWoodruff 11-Aug-16 6:35am    
A very interesting suggestion which I will follow up by a timing experiment compared to what I use now for generating fixed-length strings.
OriginalGriff 11-Aug-16 7:04am    
Interesting: I just did, and it's very slow.
Over a ten-run test, with 9804 strings (each a single line from The Chronicles of Narnia) it's about 5 times slower to use the "optimised" StringDictionary than a generic Dictionary - probably because of the "lower-case-and-culture-invariant" comparisons at a guess.

Optimised it may be, quicker it ain't! :laugh:
BillWoodruff 11-Aug-16 7:41am    
If the OP here had answered my questions, I would have posted some code. I bet you are familiar with Jeff Atwood's experiments in higher-order base encoding for increased readability, and/or Rick Strahl's later blog post ? Links on request.

In my code I use a while-loop to keep coughing up new potential ID's until I have generated as many as specified. Interestingly, using 'Contains to check if a given ID is already in the collection is many orders of magnitude faster than using 'Any.
Quote:
How to generates N no of 6 digit unique key (no duplicate)

You need a 2 steps procedure
- you need to manage a counter which have the task to give unique values. It is the only practical way to go ensure numerous unique keys over a long periods of time.
- Then you need a function that will encode that value in base 62.
The base962 function can look something like:
C#
public static string ToBase62(int Value, int Digits)
{
    char[] chars = new char[62];
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
    
    if (Digits==0) return"";
    return ToBase62(Value/(chars.Length), Digits-1).Append(chars[Value % (chars.Length)]);
}
 
Share this answer
 
v2
Comments
BillWoodruff 11-Aug-16 3:24am    
"Then you need a function that will encode that value in base 62."

Why ?
Patrice T 11-Aug-16 3:29am    
A function makes the feature easier to proof check.
It a classical base conversion and a function doing that is easy to find.
BillWoodruff 11-Aug-16 6:30am    
Think for a minute about someone relatively new to .NET reading your answer.
BillWoodruff 11-Aug-16 6:32am    
My vote of #1: the first part of this solution was already posted when this was posted, and the second part of this solution is unexplained, and very likely to be confusing to the OP or anyone else who is not familiar with the reasons to use a higher-order base-encoding.
Patrice T 11-Aug-16 9:46am    
Do you like it better now ?
OrginalGriff has answered your question very well.

You will have to use a HashTable or an ArrayList or a List<string>. What ever is generated, check if it exists in the List<string> before adding it. Keep doing this until the length of the List<string> matches your required count.

You will have to change the for() to a while(), and it might take a while too for larger maxSize.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900