Incrementing alphabets as a form of ID

Occasionally, whether you are designing or integrating APIs, you would come across the need to have unique identifier that includes alphabet(s). For example, how can we implement the following unique identifier, AANNNNNN, where NNNNN is numeric serial, and AA is the alphabetical serial. 

So, each time we need a new ID, it would be 

 AA000000,...,AA999999,AB000000,... 

 I will not go into what you should do after ZZ999999, but rather how to maintain the alphabetical side of this ID. The first thing that came into my mind would be splitting the alphabets from the numerical serial, but how can I store the alphabets as a sequence in the database? 

The solution would be to store a numeric representation of the alphabets in the database, and convert them accordingly when you read the sequence. Using Excel as an example, we would have the following, 

1: A 
... 
26: Z 
27: AA 
28: AB 
... and so on 

Since I need a 2-character alphabets, my sequence should start at 27, 'AA', and ends at 702, which is 'ZZ'. So now, how can I convert 27 to 'AA'? This can be easily done by processing the most significant digit first, and slowly move to the least significant digit, see the following example

StringBuilder sb = new StringBuilder();
        
while(n > 0)
{
	n--; // Zero based
	sb.Append((char)('A' + n % 26));
	n /= 26;
}

return new string(sb.ToString().Reverse().ToArray());

Simple right? Just remember that the ASCII representation of A ~ Z is zero based, hence, we need to add the n-- there.

Comments

Popular posts from this blog

ASP.NET Core service locator pattern

Ways to perform eager loading via NHibernate

Caching and generic query using NHibernate [.NET Core]