6May/140
Checking the validity of an NHS Number using 1 line of C#
This article is an implementation of the method for checking NHS Number validity, as described in the article:
This is an experiment to reduce the checking method to one line of code, and makes no?attempt at being efficient.?This single line, below, is arranged into 8 lines to make it easier to read.
pNHSNumber.ToCharArray().Where (i=> i>= 48 && i <=57).Count() != 10 ? false : new List() { pNHSNumber.ToCharArray() .Where((value, index) => index < 9) .Select((value, index) => (10 - index) * (value - 48)) .Sum() } .Select(i=> i % 11) .Select(i=> (11 - i) == 11 ? 0 : (11-i)) .First() == (pNHSNumber[pNHSNumber.Length - 1] - 48);
It is constructed as follows:
- Line 1: Checking the string length is 10 and consists only of digits
- Lines 2 - 5:? Multiply the first nine digits by a weighting factor and sum, storing the?result, a single value, in a generic list.
- Line 3 : select the first 9 digits of pNHSNumber.ToCharArray()
- Line 4: Multiply each of the digits by it's weighting - first digit by 10 e.g. (10 - index of 0), second digit by 9 (e.g. 10 minus index of 1) etc
- Lin 5: sum the values produced by line 4
- Line 6: Get the remainder of the sum when divided by 11
- Line 7: Subtract the remainder from 11, and if the resultant value is 11 change to 0
- Line 8: Test if the check digit is equal to last digit
Usage
Wrap up the above in a function:
bool CheckNNHSNumber (pNHSNumber string) { pNHSNumber.ToCharArray().Where (i=> i>= 48 && i <=57).Count() != 10 ? false : new List() { pNHSNumber.ToCharArray() .Where((value, index) => index < 9) .Select((value, index) => (10 - index) * (value - 48)) .Sum() } .Select(i=> i % 11) .Select(i=> (11 - i) == 11 ? 0 : (11-i)) .First() == (pNHSNumber[pNHSNumber.Length - 1] - 48); }
and call it, thusly:
//valid NHS number Console.WriteLine(CheckNHSNumber("4800963435")); //invalid NHS Number Console.WriteLine(CheckNHSNumber("4800963439"));
Leave a comment