.NET Short Unique Identifier

前端 未结 23 1117
忘掉有多难
忘掉有多难 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:21

    I know it's quite far from posted date... :)

    I have a generator which produces only 9 Hexa characters, eg: C9D6F7FF3, C9D6FB52C

    public class SlimHexIdGenerator : IIdGenerator
    {
        private readonly DateTime _baseDate = new DateTime(2016, 1, 1);
        private readonly IDictionary> _cache = new Dictionary>();
    
        public string NewId()
        {
            var now = DateTime.Now.ToString("HHmmssfff");
            var daysDiff = (DateTime.Today - _baseDate).Days;
            var current = long.Parse(string.Format("{0}{1}", daysDiff, now));
            return IdGeneratorHelper.NewId(_cache, current);
        }
    }
    
    
    static class IdGeneratorHelper
    {
        public static string NewId(IDictionary> cache, long current)
        {
            if (cache.Any() && cache.Keys.Max() < current)
            {
                cache.Clear();
            }
    
            if (!cache.Any())
            {
                cache.Add(current, new List());
            }
    
            string secondPart;
            if (cache[current].Any())
            {
                var maxValue = cache[current].Max();
                cache[current].Add(maxValue + 1);
                secondPart = maxValue.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                cache[current].Add(0);
                secondPart = string.Empty;
            }
    
            var nextValueFormatted = string.Format("{0}{1}", current, secondPart);
            return UInt64.Parse(nextValueFormatted).ToString("X");
        }
    }
    

提交回复
热议问题