Reputation: 4560
I want to add Array items inside forach loop.
My RegionalEarn
array comes like this,
[0]Region1=25
[1]Region2=50
I need final RModel.TAX
Should be 75(25+50)
But in my case it comes like 2550
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
foreach (var item in RegionalEarn)
{
RModel.TAX = RModel.TAX + item.Split('=')[1];
}
Upvotes: 0
Views: 1037
Reputation: 9296
This is a simple way to do it.
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
foreach (var item in RegionalEarn)
{
RModel.TAX = (int.Parse(RModel.TAX) * item.Split('=').Sum (p => int.Parse(p))).ToString();
}
The above will take RModel.TAX
multiply it with the sum of the values in the item array using Sum() method. This should give you the correct result.
Upvotes: 1
Reputation: 42424
You're adding strings, not numbers. You can use the TryParse method on for example the Int32 type to try convert a string to an int. The other numbers types have a similar TryParse method. If your number comes with extra signs, dots or commas, apply the the overload that accepts a FormatProvider matching the Numberstyle or a Culture the number is from.
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
var sum =0;
foreach (var item in RegionalEarn)
{
var num = 0;
if (Int32.TryParse(item.Split('=')[1], out num))
{
sum = sum + num;
}
else
{
// log error, item.Split('=')[1] is not an int
}
}
RModel.TAX = sum.ToString();
Upvotes: 2
Reputation: 326
actually you done like concatenation.it comes only string values. so try convert to int or double .
string[] RegionalEarn = tickets["EARN"].ToString().Split(',');
foreach (var item in RegionalEarn)
{
RModel.TAX = Convert.ToInt32(RModel.TAX) + Convert.ToInt32( item.Split('=')[1]);
}
Upvotes: 1