我有一个CCN需要执行luhn检查。我有大部分代码工作,但现在我需要用结果更新我的数据库,所以我知道哪些卡是有效的。这是我正在使用的一些代码:
int valid;
foreach (DataRow dr in dt.Rows)
{
string cardNumber = dr["cardNumber"].ToString();
Console.WriteLine ("{0} is {1}valid", cardNumber, cardNumber.ToString().LuhnCheck() ? "" : "not ");
valid = /*some code here*/;
SqlCommand cmd = new SqlCommand("update MyTable SET LuhnSatisfied =" + valid + " where cardNumber =" + cardNumber, con);
cmd.ExecuteNonQuery();
}
我的console.writeline语句调用LuhnCheck方法,该方法返回0或1.我需要在变量中捕获这些结果,因此我可以将其连接到我的update语句中。任何想法如何做到这一点?这是luhnCheck代码的其余部分
public static class Luhn
{
public static bool LuhnCheck(this string cardNumber)
{
return LuhnCheck(cardNumber.Select(c => c - '0').ToArray());
}
static readonly int[] results = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };
private static bool LuhnCheck(this int[] digits)
{
int checkValue = GetCheckValue(digits);
return checkValue == 0;
}
private static int GetCheckValue(int[] digits)
{
int i = 0;
int lengthMod = digits.Length % 2;
return digits.Sum(d => i++ % 2 == lengthMod ? results[d] : d) % 10;
}
}
答案 0 :(得分:0)
foreach (DataRow dr in dt.Rows)
{
string cardNumber = dr["cardNumber"].ToString();
bool isValid = cardNumber.ToString().LuhnCheck();
Console.WriteLine("{0} is {1}valid", cardNumber, isValid ? "" : "not ");
string isValidSqlBool = isValid ? "1" : "0";
SqlCommand cmd = new SqlCommand("update MyTable SET LuhnSatisfied = " + isValidSqlBool + " where cardNumber =" + cardNumber, con);
cmd.ExecuteNonQuery();
}