Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ returning strange value using Select on a string

Tags:

c#

linq

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.

like image 376
user3733107 Avatar asked Jan 21 '26 10:01

user3733107


1 Answers

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.

like image 170
Guffa Avatar answered Jan 24 '26 00:01

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!