DataTable增加平均行和汇总列

我们在得到数据后,希望对数据进计算。如下图所示。这里通过dataTable.Compute()实现行计算,DataColumn. Expression实现列计算。
DataTable增加平均行和汇总列_第1张图片
实现步骤:
1、首先我们得到数据放入DataTable中,具得到方法不作说明。
             // 得到数据
            DataTable dtVal  = GetDataTable(SQL );

2、增加一行平均行,用于计算各列的平均值。方法如下。主要使用dataTable.Compute()方法实现。
       // 增加一行求平均列
                DataRow drRow  =  dtVal.NewRow();
                
// 空的数据列
                drRow[ 0 =  DBNull.Value;
                drRow[
1 =   "" ;
                drRow[
2 =  sTypeText;
                
// 增加求平均行
                dtVal.Rows.Add(drRow);

                
// 汇总的表达式
                 string  expression  =   "" ;
       //lColName为要计算的列列表。这是城List<string>型,在别的地方赋值。这里不作说明。
                 foreach  ( string  sColName  in  lColName)
                {
                    
// 求平均
                    drRow[sColName]  =  dtVal.Compute( " Avg( "   +  sColName  +   " ) " " true " );
                }

3、增加一列求和列,用于计算此行的和。主要使用DataColumn. Expression实现
        // 汇总的表达式
                 string  expression  =   "" ;
       //lColName为要计算的列列表。这是城List<string>型,在别的地方赋值。这里不作说明。
                 foreach  ( string  sColName  in  lColName)
                {
                    
// 求平均                  
                    expression 
+=  sColName  +   " + " ;
                }
                expression 
=  expression.Trim( ' + ' );
                
// 增加汇总列
                System.Type myDataType  =  System.Type.GetType( " System.Decimal " );
                DataColumn dcCol 
=   new  DataColumn( " 汇总 " , myDataType, expression, MappingType.Attribute);
                
// 增加求和列
                dtVal.Columns.Add(dcCol);
4、最后就是呈现了。可以通过GirdView等显示。如上图。





你可能感兴趣的:(Datatable)