This code return the int 49
IEnumerable<int> numbersList = numbers.Select(x => Convert.ToInt32(x));
int sum = numbersList.Sum();
the numbers variable is a string with the value 1.
if I use
numbers.Split(',').Select(x => Convert.ToInt32(x));
Then I get the correct answer. I know split passes back a string array so I used a string array with a single value of 1 instead of splitting and that worked too.
string[] sa = new string[] { "1" }
My question is does anyone know why using the select on a string return the wrong value?
Thanks.
When you use numbers.Select() you treat the string as a collection. It is a collection, but not a collection of substrings but a collection of characters.
You get the same result as if numbers was an array of characters, i.e { '1' }.
The result of Convert.ToInt32('1') is the character code for '1', which is 49.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With