如何获取数据表中的列总和

时间:2017-05-11 10:31:31

标签: c#

我想分别计算总重量和体积列    数据表。

对于E.g

Route   Weight   Volume
R1       10       100
R1       20       200 
R2       10       50

我希望结果为

Route   Weight   Volume
R1       30       300
R2       10       50

我使用了以下代码,

   var query = from row in DTRationData.AsEnumerable()
                        group row by row.Field<string>("RouteCode") into grp
                        orderby grp.Key
                        select new
                        {
                            Id = grp.Key,
                            Sum = grp.Sum(r => r.Field<decimal>("Weight"))                           
                        };

            foreach (var grp in query)
            {
                DRow = DTRouteData.NewRow();
                DRow["RouteCode"] = grp.Id;
                DRow["Weight"] = grp.Sum/1000;                
                DTRouteData.Rows.Add(DRow);
            }

1 个答案:

答案 0 :(得分:2)

只需在匿名类型中添加其他属性:

.......
select new
{
    Id = grp.Key,
    WeightSum = grp.Sum(r => r.Field<decimal>("Weight")),
    VolumeSum = grp.Sum(r => r.Field<decimal>("Volume"))                              
};