如何获得两列相乘的和 [英] How to get sum of two columns multiplication

查看:125
本文介绍了如何获得两列相乘的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,其中有两列名为col1和col2。我想获得每一行的(col1 * col2)之和。
我正在使用以下代码。

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.


推荐答案

一种更易读的方式是使用 LINQ-To-DataSet

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") );

这篇关于如何获得两列相乘的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆