I need to validate Card number of 15 digits, for that I have to generate checksum digit to complete the number, How can I do this, I have done the following; I have a string of 15 digits, and I want to generate checksum digit to complete it. following this article regarding Luhn Algorithms I have tried like this.
public static bool IsAllDigit(string digits)
{
if (string.IsNullOrEmpty(digits))
{
return false;
}
else
{
int numberOfChar = digits.Count();
if (numberOfChar > 0)
{
bool r = digits.All(char.IsDigit);
return r;
}
else
{
return false;
}
}
}
// 5*2 1 6*2 0 6*2 1 0*2 0 0*2 0 0*2 0 3*2 6 2*2
public static string GenerateCRC(string digits)
{
int[] firstRow = new int[15];
string CRC = string.Empty;
if (IsAllDigit(digits))
{
var array = digits.Select(ch => ch - '0').ToArray();
for (int i = 0; i < array.Length; i++)
{
if (i%2==0)
{
var temp = array[i] * 2;
if (temp > 9)
{
var arr = temp.ToString().Select(t => int.Parse(t.ToString())).ToArray();
int f = arr.Sum();
firstRow[i] = f;
}
else
{
firstRow[i] = array[i]*2;
}
}
else
{
firstRow[i] = array[i];
}
}
var sum = firstRow.Sum();
int crc = sum % 10;
CRC = crc.ToString();
}
return CRC;
}
Is this a best way to implement this and then validate number. Although it gives correct results but this can be summarize or done in smart way. Suggestions please.