DataTable中列求和的方法

来源:互联网 发布:js tochararray 编辑:程序博客网 时间:2024/06/05 20:54

在项目做报表中经常需要对某列进行求和统计

传统我方法是通过For 或Foreach遍历相加来统计.

最近发现一DataTable的有系统自带的方法,可以实现求和统计的方法Compute,下面分享给大家

public Object Compute(string expression,string filter)
expression:计算表达式(加、减、乘、除)
Type: System.String

The expression to compute.

filter :筛选条件(格式与Sql条件一样)
Type: System.String

The filter to limit the rows that evaluate in the expression.

returnvalue:返回值是object类型

例如

DataTable dt = new DataTable();
int sumCount=0  

object obj=dt.Compute("sum(字段名)","条件");

if(obj!=null && !  string.IsNullOrEmpty(obj.ToString()))

{

   sumCount=int.Parse(obj);

}