Auto Generate alphanumeric Unique Id with C#

后端 未结 5 559
忘了有多久
忘了有多久 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 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.

提交回复
热议问题