.NET Short Unique Identifier

前端 未结 23 1102
忘掉有多难
忘掉有多难 2020-12-07 11:27

I need a unique identifier in .NET (cannot use GUID as it is too long for this case).

Do people think that the algorithm used here is a good candidate or do you have

相关标签:
23条回答
  • 2020-12-07 12:06

    This one a good one - http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx

    and also here YouTube-like GUID

    You could use Base64:

    string base64Guid = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
    

    That generates a string like E1HKfn68Pkms5zsZsvKONw==. Since a GUID is always 128 bits, you can omit the == that you know will always be present at the end and that will give you a 22 character string. This isn't as short as YouTube though.

    0 讨论(0)
  • 2020-12-07 12:06

    I use a similar approach as Dor Cohen's but removing some special characters:

    var uid = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", "");     
    

    This will output just alphanumeric characters. The UIDs are not guaranteed to have always the same length. Here is a sample run:

    vmKo0zws8k28fR4V4Hgmw 
    TKbhS0G2V0KqtpHOU8e6Ug 
    rfDi1RdO0aQHTosh9dVvw
    3jhCD75fUWjQek8XRmMg 
    CQUg1lXIXkWG8KDFy7z6Ow 
    bvyxW5aj10OmKA5KMhppw
    pIMK8eq5kyvLK67xtsIDg
    VX4oljGWpkSQGR2OvGoOQ 
    NOHBjUUHv06yIc7EvotRg
    iMniAuUG9kiGLwBtBQByfg
    
    0 讨论(0)
  • 2020-12-07 12:06

    In C# a long value has 64 bits, which if encoded with Base64, there will be 12 characters, including 1 padding =. If we trim the padding =, there will be 11 characters.

    One crazy idea here is we could use a combination of Unix Epoch and a counter for one epoch value to form a long value. The Unix Epoch in C# DateTimeOffset.ToUnixEpochMilliseconds is in long format, but the first 2 bytes of the 8 bytes are always 0, because otherwise the date time value will be greater than the maximum date time value. So that gives us 2 bytes to place an ushort counter in.

    So, in total, as long as the number of ID generation does not exceed 65536 per millisecond, we can have an unique ID:

    // This is the counter for current epoch. Counter should reset in next millisecond
    ushort currentCounter = 123;
    
    var epoch = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    // Because epoch is 64bit long, so we should have 8 bytes
    var epochBytes = BitConverter.GetBytes(epoch);
    if (BitConverter.IsLittleEndian)
    {
        // Use big endian
        epochBytes = epochBytes.Reverse().ToArray();
    }
    
    // The first two bytes are always 0, because if not, the DateTime.UtcNow is greater 
    // than DateTime.Max, which is not possible
    var counterBytes = BitConverter.GetBytes(currentCounter);
    if (BitConverter.IsLittleEndian)
    {
        // Use big endian
        counterBytes = counterBytes.Reverse().ToArray();
    }
    
    // Copy counter bytes to the first 2 bytes of the epoch bytes
    Array.Copy(counterBytes, 0, epochBytes, 0, 2);
    
    // Encode the byte array and trim padding '='
    // e.g. AAsBcTCCVlg
    var shortUid = Convert.ToBase64String(epochBytes).TrimEnd('=');
    
    0 讨论(0)
  • 2020-12-07 12:07

    You can try with the following library:

    • https://hashids.org
    • https://www.nuget.org/packages/Hashids.net/
    0 讨论(0)
  • 2020-12-07 12:08

    IDENTITY values should be unique in a database, but you should be aware of the limitations... for example, it makes bulk data inserts basically impossible which will slow you down if you're working with a very large number of records.

    You may also be able to use a date/time value. I've seen several databases where they use the date/time to be the PK, and while it's not super clean - it works. If you control the inserts, you can effectively guarantee that the values will be unique in code.

    0 讨论(0)
  • 2020-12-07 12:10

    Simple usable package. I use it for temporal request id generator.

    https://www.nuget.org/packages/shortid

    https://github.com/bolorundurowb/shortid

    Uses System.Random

    string id = ShortId.Generate();
    // id = KXTR_VzGVUoOY
    

    (from the github page)

    If you want to control the type of id generated by specifying whether you want numbers, special characters and the length, call the Generate method and pass three parameters, the first a boolean stating whether you want numbers, the second a boolean stating whether you want special characters, the last a number indicating your length preference.

    string id = ShortId.Generate(true, false, 12);
    // id = VvoCDPazES_w
    
    0 讨论(0)
提交回复
热议问题