• DataTable增加平均行和汇总列


    我们在得到数据后,希望对数据进计算。如下图所示。这里通过dataTable.Compute()实现行计算,DataColumn.Expression实现列计算。

    实现步骤:
    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等显示。如上图。





  • 相关阅读:
    蓝桥杯 十六进制转八进制
    蓝桥杯 字母图形
    2017.12.13T19_B2_5mianshiti
    2017.11.21T19_B2_6.2讲义
    2017.12.13T19_B2_6zuoye
    2017.12.1T19_B2_5zuoye
    2017.12.1T19_B2_4zuoye
    2017.12.1T19_B2_4——2
    2017.12.1T19_B2_4.3kehouzuoye
    2017.12.1T19_B2_4.2
  • 原文地址:https://www.cnblogs.com/scottckt/p/1528601.html
Copyright © 2020-2023  润新知