问题
I have a datatable in which there are two column named col1 and col2. I want to get sum of (col1 * col2) of each row. i am using following code..
object sumObject;
sumObject = dt.Compute("Sum(col1* col2)", "(id = '" + id+ "') ");
But it doesn't worked. It produces an error as :
Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.
回答1:
A more readable way is using LINQ-To-DataSet
:
int sumTotal = dt.AsEnumerable()
.Where(r => r.Field<int>("id") == id)
.Sum(r => r.Field<int>("col1") * r.Field<int>("col2") );
回答2:
double dTotal = 0.0;
foreach (DataRow dr in dt.Rows)
{
double dValue1, dValue2;
if (!double.TryParse(dr["col1"].ToString(), out dValue1))
{
//error parsing
break;
}
if (!double.TryParse(dr["col2"].ToString(), out dValue2))
{
//error parsing
break;
}
dTotal += dValue1 * dValue2;
}
来源:https://stackoverflow.com/questions/22957369/how-to-get-sum-of-two-columns-multiplication