Harry89pl
Harry89pl

Reputation: 2435

How to use Sum on array of strings - LINQ?

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

Answers (3)

SLaks
SLaks

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

ΩmegaMan
ΩmegaMan

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

yoozer8
yoozer8

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

Related Questions