簡體   English   中英

使用C#自動生成字母數字唯一ID

[英]Auto Generate alphanumeric Unique Id with C#

字符串總長度為5個字符

我有一個場景,ID開頭

A0001以A9999結束,然后以B0001至B9999結束,直至F0001至f9999

之后

FA001到FA999然后FB001到FB999直到.... FFFF9

請提出有關如何創建此格式的任何建議。

public static IEnumerable<string> Numbers()
{
    return Enumerable.Range(0xA0000, 0xFFFF9 - 0xA0000 + 1)
        .Select(x => x.ToString("X"));
}

你也可以有一個id生成器類:

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");
    }
}

看到這段代碼

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();

}

我遲到了幾年。 但我希望我的回答能幫助每個人尋找一個好的ID生成器。 之前的asnswers沒有按預期工作,也沒有回答這個問題。

我的答案非常符合要求。 和更多!!!

請注意,將_fixedLength設置為ZERO將創建動態大小的ID。 將其設置為其他任何內容都將創建FIXED LENGTH ID;

另請注意,調用帶有當前ID的重載將“播種”該類,並且不需要使用另一個ID調用連續調用。 除非你有隨機ID,並且每個都需要下一個ID。

請享用!

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();
  }
}

這是使用_fixedLength = 4和_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 AB04 AB05 AC01 AC02 AC03 AC04 AC05

運行此查詢以獲取數據庫中的最后一個ID

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

將結果讀取到變量,然后對結果運行以下函數以獲取下一個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;
}

免責聲明
此代碼僅生成第一組ID。 我不明白生成第二組的過程。

如果您需要從數據庫中獲取它並執行此操作,您可以使用以下內容。

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

這應該為您提供從數據庫ID直接轉換所需的格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM