Increment Guid in C#

后端 未结 4 750
一向
一向 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:40

    Thanks to Thomas Levesque's byte order, here's a nifty LINQ implementation:

    static int[] byteOrder = { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };
    
    static Guid NextGuid(Guid guid)
    {
        var bytes = guid.ToByteArray();
        var canIncrement = byteOrder.Any(i => ++bytes[i] != 0);
        return new Guid(canIncrement ? bytes : new byte[16]);
    }
    

    Note it wraps around to Guid.Empty if you manage to increment it that far.

    It would be more efficient if you were to keep incrementing a single copy of bytes rather than calling ToByteArray on each GUID in turn.

提交回复
热议问题