Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 423
Harry89pl Avatar asked Jan 10 '13 17:01

Harry89pl


1 Answers

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)

like image 123
SLaks Avatar answered Sep 28 '22 03:09

SLaks