Try this:
const int offset = (int) '0';
var intArray = stringArray.Select(x => ((int) x) - offset).ToArray();
The problem with your code is that char
values are internally represented as integers. However, the integer value is the code of the character, not the value of that character converted to integer. For instance the code of the character 0
is the integer 48
, according to the ASCII character table.
The above code takes the value of the character '0'
and subtracts it from the character value of your array. This works, because in ASCII digits are stored sequentially - the digits from 0
to 9
are spread from code 48
to code 57
. Subtracting the code value of zero, will essentially generate the result you desire. The good thing about this approach, is that it does not depend on the default encoding you are using (although I don't know if there is an encoding which does not respect the ASCII characters' order), and because you do not need to memorize the character code yourself.