【问题标题】:Datatable's Compute Function For RowsDatatable 的行计算函数
【发布时间】:2010-09-25 13:01:20
【问题描述】:

我们知道,通过数据表的计算功能,我们可以得到列的总和。 但我想得到一行数据表的总和。 我将举例说明:

我有一个如下图所示的数据表:使用计算函数,我们可以获得每列(产品)的总和。比如product1, 2 + 12 + 50 + 13= 77。

我想得到 company1 的总和:2 + 6 + 4 + 3 + 5 = 20

http://img123.imageshack.us/img123/1517/61519307xx5.jpg

如何使用 asp.net 1.1 做到这一点?

【问题讨论】:

  • 哇,你真的进入了石器时代! ;-)

标签: asp.net datatable


【解决方案1】:

我们可以将 Datatable 的 Compute() 函数用于以下目的:

  • 求和。
  • 求最大值。
  • 求最小值。
  • 计算平均值。

以下链接详细解释了Datatable的compute()函数:

http://codevariation.blogspot.com/2017/02/using-datatable-compute-function-in-cnet.html

希望这会对你有所帮助。

谢谢。

【讨论】:

    【解决方案2】:

    既然你想在 1.1 中解决这个问题,那么你可以做一个简单的解决方案

    DataColumn totalColumn = new DataColumn();
    totalColumn.DataType = System.Type.GetType("System.Int32");
    totalColumn.ColumnName = "Total";
    totalColumn.Expression = "Product1 + Product2 + Product3 + Product4 + Product5";
    
    // Populate and get the DataTable dt then add this computed column to this table
    
    dt.Columns.Add(totalColumn);
    //Now if you access the column "Total" of the table you will get the desired result.
    

    【讨论】:

      【解决方案3】:

      LINQ 救援:

      DataTable dt = WhateverCreatesDataTable();
      DataRow dr = dt.Rows[0];
      int sum = dt.Columns.Cast<DataColumn>().Sum(dc=>(int)dr[dc]);
      

      对于那些仍然在石器时代(又名 pre-.Net 3.5 和 LINQ)的人:

      DataTable dt = WhateverCreatesDataTable();
      DataRow dr = dt.Rows[0];
      int sum = 0;
      
      foreach(DataColumn dc in dt.Columns)
        sum += (int)dr[dc];
      

      【讨论】:

      • 然后把它放在你的问题中。
      【解决方案4】:

      来自msdn

      如果您必须对 两列或更多列,您应该创建 一个 DataColumn,设置它的 Expression 属性到适当的表达式, 并在 结果列。在这种情况下,给定 一个名为“total”的数据列, 并将 Expression 属性设置为 这个:

      "Quantity * UnitPrice"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多