使用linq汇总数据表列

时间:2013-05-11 16:16:08

标签: c# asp.net linq datatable

大家好我在数据表中的数据如下

SKU  Quantity  UnitPrice  LinePrice
 A     10         2         20
 A     10         2         20
 B     10         2         40

我想用重复记录总结SKU并得到如下结果

SKU  Quantity  UnitPrice  LinePrice
 A     20         2         40
 B     10         2         40

我试过这个但没有运气

var query = from row in lDTSalesOrder.AsEnumerable()
                            group row by row.Field<string>("SKU") into grp
                            orderby grp.Key
                            select new
                            {
                                Id = grp.Key,
                                Sum = grp.Sum(r => r.Field<double>("UnitPrice"))
                            };

1 个答案:

答案 0 :(得分:3)

在您的示例输出中,您实际上并未总计单价,但听起来您想要的是这样的:

var results = 
    from row in lDTSalesOrder
    group row by row.Field<string>("SKU") into grp
    orderby grp.Key
    select new
    {
        SKU = grp.Key,
        Quantity = grp.Sum(r => r.Field<double>("Quantity")),
        UnitPrice = grp.Sum(r => r.Field<double>("UnitPrice")),
        LinePrice = grp.Sum(r => r.Field<double>("LinePrice"))
    };

这将产生:

SKU  Quantity  UnitPrice  LinePrice
 A     20         4         40
 B     10         2         40

如果您真的想为第一个结果记录生成2的单价,Sum不是您想要的;你将不得不使用其他一些聚合函数。 MinMaxAverage甚至Select(...).First()会产生这种结果,但您必须更准确地定义输出中的内容。你也可以这样做:

var results = 
    from row in lDTSalesOrder
    group row by new { SKU = row.Field<string>("SKU"), UnitPrice = row.Field<string>("UnitPrice") } into grp
    orderby grp.Key.SKU
    select new
    {
        SKU = grp.Key.SKU,
        Quantity = grp.Sum(r => r.Field<double>("Quantity")),
        UnitPrice = grp.Key.UnitPrice,
        LinePrice = grp.Sum(r => r.Field<double>("LinePrice"))
    };

任何这些选项都会产生:

SKU  Quantity  UnitPrice  LinePrice
 A     20         2         40
 B     10         2         40