Auto Generate alphanumeric Unique Id with C#

后端 未结 5 560
忘了有多久
忘了有多久 2021-01-18 12:49

Total string length is 5 chars

I have a scenario, ID starts with

A0001 and ends with A9999 then B0001 to B9999 until F0001 to f9999

after that

相关标签:
5条回答
  • 2021-01-18 12:58

    see this code

    private void button1_Click(object sender, EventArgs e)
    {   
        string get = label1.Text.Substring(7); //label1.text=ATHCUS-100
        MessageBox.Show(get);
        string ou="ATHCUS-"+(Convert.ToInt32(get)+1).ToString();
        label1.Text = ou.ToString();
    
    }
    
    0 讨论(0)
  • 2021-01-18 13:03

    Run this query in order to get the last ID in the database

    SELECT TOP 1 [ID_COLUMN] FROM [NAME_OF_TABLE] ORDER BY [ID_COLUMN] DESC
    

    Read the result to a variable and then run the following function on the result in order to get the next ID.

    public string NextID(string lastID)
    {
        var allLetters = new string[] {"A", "B", "C", "D", "E", "F"};
        var lastLetter = lastID.Substring(0, 1);
        var lastNumber = int.Parse(lastID.Substring(1));
    
        if (Array.IndexOf(allLetters, lastLetter) < allLetters.Length - 1 && 
            lastNumber == 9999) 
        {
            //increase the letter
            lastLetter = allLetters(Array.IndexOf(allLetters, lastLetter) + 1);
            lastNumber = 0;
        } else {
            lastLetter = "!";
        }
    
        var result = lastLetter + (lastNumber + 1).ToString("0000");
    
        //ensure we haven't exceeded the upper limit
        if (result.SubString(0, 1) == "!") {
            result = "Upper Bounds Exceeded!";
        }
    
        return result;
    }
    

    DISCLAIMER
    This code will only generate the first set of IDs. I do not understand the process of generating the second set.

    0 讨论(0)
  • 2021-01-18 13:09
    public static IEnumerable<string> Numbers()
    {
        return Enumerable.Range(0xA0000, 0xFFFF9 - 0xA0000 + 1)
            .Select(x => x.ToString("X"));
    }
    

    You could also have an id generator class:

    public class IdGenerator
    {
        private const int Min = 0xA0000;
        private const int Max = 0xFFFF9;
        private int _value = Min - 1;
    
        public string NextId()
        {
            if (_value < Max)
            {
                _value++;
            }
            else
            {
                _value = Min;
            }
            return _value.ToString("X");
        }
    }
    
    0 讨论(0)
  • 2021-01-18 13:10

    I am a few years late. But I hope my answer will help everyone looking for a good ID Generator. NON of the previous asnswers work as expected and do not answer this question.

    My answer fits the requirements perfectly. And more!!!

    Notice that setting the _fixedLength to ZERO will create dynamically sized ID's. Setting it to anything else will create FIXED LENGTH ID's;

    Notice also that calling the overload that takes a current ID will "seed" the class and consecutive calls DO NOT need to be called with another ID. Unless you had random ID's and need the next one on each.

    Enjoy!

    public static class IDGenerator
    {
      private static readonly char _minChar = 'A';
      private static readonly char _maxChar = 'C';
      private static readonly int _minDigit = 1;
      private static readonly int _maxDigit = 5;     
      private static int _fixedLength = 5;//zero means variable length
      private static int _currentDigit = 1;
      private static string _currentBase = "A"; 
    
      public static string NextID()
      {                
        if(_currentBase[_currentBase.Length - 1] <= _maxChar)
        {
          if(_currentDigit <= _maxDigit)
          {
            var result = string.Empty;
            if(_fixedLength > 0)
            {             
              var prefixZeroCount = _fixedLength - _currentBase.Length;
              if(prefixZeroCount < _currentDigit.ToString().Length)
                throw new InvalidOperationException("The maximum length possible has been exeeded.");
              result = result = _currentBase + _currentDigit.ToString("D" + prefixZeroCount.ToString());
            }
            else
            {
              result = _currentBase + _currentDigit.ToString();
            }            
            _currentDigit++;
            return result;
          }
          else
          {
            _currentDigit = _minDigit;
            if(_currentBase[_currentBase.Length - 1] == _maxChar)
            {
              _currentBase = _currentBase.Remove(_currentBase.Length - 1) + _minChar;
              _currentBase += _minChar.ToString();
            }
            else
            {
              var newChar = _currentBase[_currentBase.Length - 1];
              newChar++;
              _currentBase = _currentBase.Remove(_currentBase.Length - 1) + newChar.ToString();
            }
    
            return NextID();
          }
        }
        else
        {         
            _currentDigit = _minDigit;
            _currentBase += _minChar.ToString();
           return NextID();            
    
        }      
      }
    
      public static string NextID(string currentId)
      {
        if(string.IsNullOrWhiteSpace(currentId))
          return NextID();
    
        var charCount = currentId.Length;
        var indexFound = -1;
        for(int i = 0; i < charCount; i++)
        {
          if(!char.IsNumber(currentId[i]))
            continue;
    
          indexFound = i;
          break;
        }
        if(indexFound > -1)
        {
          _currentBase = currentId.Substring(0, indexFound);
          _currentDigit = int.Parse(currentId.Substring(indexFound)) + 1;
        }
        return NextID();
      }
    }
    

    This is a sample of the ouput using _fixedLength = 4 and _maxDigit = 5

    A001 A002 A003 A004 A005 B001 B002 B003 B004 B005 C001 C002 C003 C004 C005 AA01 AA02 AA03 AA04 AA05 AB01 AB02 AB03 AB04 AB05 AC01 AC02 AC03 AC04 AC05

    0 讨论(0)
  • 2021-01-18 13:12

    If you need to take it from the database and do this you can use something like the following.

    int dbid = /* get id from db */
    string id = dbid.ToString("X5");
    

    This should give you the format you are looking for as a direct convert from the DB ID.

    0 讨论(0)
提交回复
热议问题