Reputation: 2435
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.
Upvotes: 5
Views: 12490
Reputation: 888283
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)
Upvotes: 22
Reputation: 31721
var value = "1,2,4,8,16".Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select (str => int.Parse(str))
.Sum ( ) ;
Console.WriteLine( value ); // 31
Upvotes: 0
Reputation: 7489
Instead of
int number = myString.Split(',').Sum((x,y)=> y += int.Parse(x));
use
int number = myString.Split(',').Sum(x => int.Parse(x));
which will parse each element of myString.Split(',')
to ints and add them.
Upvotes: 4