5

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.

3 Answers 3

22

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)

Sign up to request clarification or add additional context in comments.

10 Comments

first form works for me:) but second not really got error(cannot choose method from method group did you intend to invoke the method):(
I'm getting an error on the second form as well. Ambiguity between System.Func<string, int?> and System.Func<string, int>
@harry180: The second form requires C# 4+
@SLaks: What exactly changed in 4.0 to allow this? Why doesn't it work in previous versions?
|
4

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.

Comments

0
var value = "1,2,4,8,16".Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select (str => int.Parse(str))
                        .Sum ( ) ;

Console.WriteLine( value ); // 31

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.