Increment Guid in C#

后端 未结 4 749
一向
一向 2021-01-17 18:32

I have an application that has a guid variable which needs to be unique (of course). I know that statistically any guid should just be assumed to be unique, but due to dev/t

4条回答
  •  离开以前
    2021-01-17 18:45

    Verified Solution for Ordered Strings:

        private static Guid Increment(Guid guid)
        {
    
            byte[] bytes = guid.ToByteArray();
    
            byte[] order = { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };
    
            for (int i = 0; i < 16; i++)
            {
                if (bytes[order[i]] == byte.MaxValue)
                {
                    bytes[order[i]] = 0;
                }
                else
                {
                    bytes[order[i]]++;
                    return new Guid(bytes);
                }
            }
    
            throw new OverflowException("Congratulations you are one in a billion billion billion billion etc...");
    
        }
    

    Verification:

        private static Guid IncrementProof(Guid guid, int start, int end)
        {
    
            byte[] bytes = guid.ToByteArray();
    
            byte[] order = { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };
    
            for (int i = start; i < end; i++)
            {
                if (bytes[order[i]] == byte.MaxValue)
                {
                    bytes[order[i]] = 0;
                }
                else
                {
                    bytes[order[i]]++;
                    return new Guid(bytes);
                }
            }
    
            throw new OverflowException("Congratulations you are one in a billion billion billion billion etc...");
    
        }
    
        static void Main(string[] args)
        {
    
            Guid temp = new Guid();
    
            for (int j = 0; j < 16; j++)
            {
                for (int i = 0; i < 255; i++)
                {
                    Console.WriteLine(temp.ToString());
                    temp = IncrementProof(temp, j, j + 1);
                }
            }
    
        }
    

提交回复
热议问题