在DataTable中对行(Group By)求和

时间:2013-12-12 17:27:17

标签: c# linq datatable linq-to-dataset

我有DataTable这样的

ProductId CountThisWeek CountLastWeek
        1            10            15         
        1            20             5

        2             5            10
        2            10            15
        2            10            20

        3            10            15

我需要通过“压缩”(由productId求和)我的初始DataTable来获取新的DataTable,如下所示:

ProductId CountThisWeek CountLastWeek
        1            30            20         
        2            25            45
        3            10            15

有没有办法使用LINQ或其他技术来实现它(.NET 3.5)?

1 个答案:

答案 0 :(得分:4)

from r in table.AsEnumerable()
group r by r.Field<int>("ProductId") into g
select new {
   ProductId = g.Key,
   CountThisWeek = g.Sum(r => r.Field<int>("CountThisWeek")),
   CountLastWeek = g.Sum(r => r.Field<int>("CountLastWeek"))
}

您可以使用CopyToDataTable()方法从这些匿名对象创建新的DataTable