I have a program which validates a 13 digit ISBN number. How could I change the code so that it can run without using LINQ. I have linked my code below.
using System;
using System.Linq;
public class Program
{
public static void Main() {
Console.WriteLine(CheckISBN13("978-1734314502"));
Console.WriteLine(CheckISBN13("978-1734314509"));
Console.WriteLine(CheckISBN13("978-1788399081"));
Console.WriteLine(CheckISBN13("978-1788399083"));
static bool CheckISBN13(string code) {
code = code.Replace("-", "").Replace(" ", "");
if (code.Length != 13) return false;
int sum = 0;
foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) {
if (char.IsDigit(digit)) sum = (digit - '0') * (index % 2 == 0 ? 1 : 3);
else return false;
}
return sum % 10 == 0;
}
}
}
CodePudding user response:
Yeah it's a bit of a ridiculous use of linq to be honest, given that strings can be enumerated/indexed directly there isn't any need to use linq to effectively turn them into a "char plus index the char is at" tuple..
At an untested guess the linqy bit would look like :
int index = 0;
foreach (var digit in code) {
if (char.IsDigit(digit))
sum = (digit - '0') * (index % 2 == 0 ? 1 : 3);
else
return false;
}
Or perhaps, a for:
for(int index = 0; index < code.Length; index ) {
var digit = code[index](
if (char.IsDigit(digit))
sum = (digit - '0') * (index % 2 == 0 ? 1 : 3);
else
return false;
}
So what was the linq bit doing before? One of the overloads of Select will enumerate the enumerable and, as well as giving you the "thing at the position" (which in this case is a char on the string) also gives you "the int index of the position". In essence, the linq takes a string like "hello world" and gives you:
h 0
e 1
l 2
l 3
o 4
And so on.. but the crackers thing is you can run eg a normal for loop with an int index (which is the 0,1,2,3,4...) and ask a string for the char at the index; "hello world"[index]
gives you e
when index is 1
etc.. so by having the index and the string you can have the char, and the char plus index is the pair of things the LINQ gave you from the string..
LINQ's a hammer; not every problem is a nail