How to sum array of strings with LINQ Sum method?
I have string which looks like: "1,2,4,8,16"
I have tried:
string myString = "1,2,4,8,16";
int number = myString.Split(',').Sum((x,y)=> y += int.Parse(x));
But it says that cannot Parse
source type int
to type ?.
I do not want to use a foreach
loop to sum this numbers.
You're mis-calling Sum()
.
Sum()
takes a lambda that transforms a single element into a number:
.Sum(x => int.Parse(x))
Or, more simply,
.Sum(int.Parse)
This only works on the version 4 or later of the C# compiler (regardless of platform version)
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