Reputation: 365
i have got a store procedure returning 4 different tables, so i have created four different datatable objects
DataTable dt1 = ds.Tables[0];
DataTable dt2 = ds.Tables[1];
DataTable dt3 = ds.Tables[2];
DataTable dt4 = ds.Tables[3];
the second table dt2 contains two columns address and completed
address1................12
address2.................9
address3................14
address4................13
i want to loop through second datatable and add all completed values and store it in local variable comp my solution as as follow
int comp = 0;
foreach (DataRow dr in dt2.Rows)
{
object o = dr["Completed"];
comp =+ Convert.ToInt32(o);
}
but output of comp
is 13 but it should be 48 sum of last column second datatable, any ideas
Upvotes: 1
Views: 888
Reputation: 223322
Adil has rightly pointed out to the mistake , you can also use LINQ To DataSet/DataTable to compute SUM
like:
int comp = dt2.AsEnumerable()
.Sum(r => r.Field<int>("Completed"));
Or you can use DataTable.Compute
like:
int comp = Convert.ToInt32(dt2.Compute("Sum(Completed)", ""));
Upvotes: 2
Reputation: 148150
You are using wrong operator for assignment with addition You need +=
instead of =+
. The operator you have =+
mean you have + unary addition operator with +Convert.ToInt32(o)
and result is assigned to object o
comp =+ Convert.ToInt32(o);
Means
comp = +Convert.ToInt32(o); Addition operator will be considered unary operator with Convert.ToInt32(o)
Your code would be
foreach (DataRow dr in dt2.Rows)
{
object o = dr["Completed"];
comp += Convert.ToInt32(o);
}
If the left operand of a += or -= operator is classified as an event access, then the expression is evaluated as follows:
- The instance expression, if any, of the event access is evaluated.
- The right operand of the += or -= operator is evaluated, and, if required, converted to the type of the left operand through an implicit conversion (Section 6.1).
- An event accessor of the event is invoked, with the argument list consisting of the right operand, after evaluation and, if necessary, conversion. If the operator was +=, the add accessor is invoked. If the operator was -=, the remo ve accessor is invoked, MSDN.
Upvotes: 2