How to get sum of two columns multiplication

谁都会走 提交于 2020-07-07 04:09:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!