[Solved] How can I convert this program so it doesn’t use LINQ?


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..

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

solved How can I convert this program so it doesn’t use LINQ?