【问题标题】:c# datatable summary same row value in new rowc#数据表汇总新行中的相同行值
【发布时间】:2022-09-30 19:10:41
【问题描述】:

如何在 c# 中使用数据表求和相同的单元格值并将其显示在新行中。 就像下面的图片链接:对于相同的价格值总和大小值并在特定价格的新行中显示。

Click to open picture

感谢帮助!

马克·琼斯

    标签: c# datatable summary


    【解决方案1】:

    创建一个数据行:

    DataTable dt=new DataTable();//For example use your data table
    //Creating a data row for calculating
    DataRow Fndr = dt.NewRow();
    //Here i added on 0th cell you can add anywhere based on data
    Fndr[0] = "Total";
    

    计算:

    decimal d = 0;
    for (int l = 1; l < dt.Columns.Count; l++)
    {
        string s = dt.Columns[l].ColumnName.ToString();
        decimal total = dt.AsEnumerable()
            .Where(r => !r.IsNull(dt.Columns[l].ColumnName.ToString()) 
                      && decimal.TryParse(r[dt.Columns[l].ColumnName.ToString()].ToString(), out d))
            .Sum(r => d);
        Fndr[l] = total;
    }
    

    【讨论】:

    • 您可以简化一些部分:您不需要使用ColumnName,您应该直接使用DataColumn,否则必须找到带有名称的列。所以使用:.Select(r=&gt; !r.IsNull(dt.Columns[l]) &amp;&amp; decimal.TryParse(r[dt.Columns[l]].ToString() ...)。最好直接选择decimal?,然后用Where 过滤。然后你不需要从不同的范围访问变量d。这很容易出错。
    猜你喜欢
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2021-08-05
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多