0

I need to add arraylist of items in linq.Below is my sample code.

string[] _str = ("1.21,2.02,3.14,4.951,5.156").ToString().Split(',');
double Sum = 0.0;
for (int i = 0; i < _str.Length; i++)
{
  if (_str[i].ToString() != ",")
     Sum = Sum + Convert.ToDouble(_str[i]);
}

The above code i have done in for loop to get the sum of all items in the array list. I need to convert the same operation in linq.Please anyone help me solve this since i'm new to linq.

Thanks in advance.

2
  • 1
    Why do you need to do it in LINQ? Commented Sep 11, 2012 at 10:44
  • 2
    The first line is so redundant. Commented Sep 11, 2012 at 10:44

4 Answers 4

3

Use the Sum method:

string[] _str = "1.21,2.02,3.14,4.951,5.156".Split(',');
var result = _str.Sum(e => Double.Parse(e));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply,if suppose a value that is coming from DB is like this 1.21,2.02,3.14,4.951,5.156, . Is there any code change will occur.
@Neon Sorry, I don't understand you.
1
string[] _str =  {"1.21","2.02","3.14","4.951","5.156"};
double Sum = 0.0;
for (int i = 0; i < _str.Length; i++)
{
    double.TryParse(_str[i],out val)
}

But if you are doing this for sake of learning linq

string[] _str = {"1.21","2.02","3.14","4.951","5.156"};
_str.Sum(x => 
    {  
       double val ; 
       if(double.TryParse(x, out val)){
         return val;
       }
       return 0.0;
    });

If you are sure that the string will always contain valid numeric strings. Then you can just use double.Parse(x).

Comments

0

You can try

string[] _str = "1.21,2.02,3.14,4.951,5.156".Split(',');
double Sum = _str.Sum(x=>Convert.ToDouble(x));

Comments

0

Try...

var _str = _str = ("1.21,2.02,3.14,4.951,5.156").ToString().Split(',');
var _sum = Array.ConvertAll<String, Double>(_str, Double.Parse).Sum();

Another one liner, with method chaining example...

var _sum = "1.21,2.02,3.14,4.951,5.156".Split(',').Sum(x => Double.Parse(x));

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.