简体   繁体   中英

Validate and sort a variety of serial numbers with different formats?

I am faced with the following issue. I need to capture a range of serial numbers in c# to be stored in a database. If these serial numbers are just numbers, it is fine, but I have ran into serial numbers which are alpha-numeric such as:

56AAA71064D6 and 56AAA7105A25

How can I accommodate the different possibilities that serial number ranges may be in?

Assuming that all serial numbers have some order, how can I parse the sequential part of it?

The database takes the serial numbers as strings already.

If your database assumes the serial number is numeric, you either need to change that part of the DB to allow alphanumeric values, or else define a new mapping table to correlate the external serial number with a unique numeric ID so that you can continue to use numbers for the database's internal representation of a serial 'number'.

You'd also have to add support to hand out a new, unique internal serial number for a given alphanumeric input in a concurrency-safe way.

EDIT: What I mean by this is that when a new alphanumeric serial number has to be registered in the DB, you should do this with a transaction that atomically adds a record to the original (numeric) serial number list and adds a second record in the new table that correlates the numeric value with the alphanumeric value. If this is not atomic then the scheme breaks down. Removals have to be handled atomically also.

If your serial numbers have same width then its easy...

you have to use string.compare method to get the range.

int MaxLength = 20;

private string Pad(string val){
   if(val.Length < 20){
      val = new String('0', MaxLength - val.Length) + val;
   }
   return val;
}

public bool IsBetween(string num, string start, string end){
    num = Pad(num);
    start = Pad(num);
    end = Pad(num);
    return String.Compare(num,start)>=0 && String.Compare(num,end)<=0;
}

And if you sort all serial numbers, then you can easily pickup range.

If they are not of same width then you have to padd 0 before smaller length strings to make them all same size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM