使用Linq进行GroupBy和Sum数据表 [英] Using Linq to GroupBy and Sum datatable

查看:783
本文介绍了使用Linq进行GroupBy和Sum数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据表:


Id             Amount 1        Amount 2        Amount 3  
1              2               2               2  
12             4               6               4  
12             6               6               5  
22             7               2               1  
22             7               2               2

我需要这样获取数据表:


Id             Amount 1        Amount 2        Amount 3  
1              2               2               2  
12             10              12              9    
22             14              4               3

我最初尝试使用匿名方法来执行此操作,但是我需要将其返回到另一个使用匿名方法无法完成的类. 我的第二次尝试是这样做,以便可以将其返回:

I originally tried to do it in an anonymous method but I need to return it to another class which cannot be done with anonymous method. My second attempt was to do this so it can be returned:

DataTable ddt = dt.AsEnumerable()
        .Sum(g => g.Field<int>("Amount 1"))
        .GroupBy(g => new { Col1 = g["ID"] })
        .Select(g => g.OrderBy(r => r["ID"]).First())
        .CopyToDataTable();

此代码绝对不会编译,但是如果有任何帮助/建议,我们将不胜感激.我是linq的新手.

This code definitely wont compile but Any help/advice if possible would be really appreciated. I'm very new to linq.

推荐答案

您可以先GroupBy,然后将组投影到DataRow s,然后使用CopyToDataTable扩展名创建DataTable:

You can GroupBy first, then project the groups to DataRows, then create the DataTable using CopyToDataTable extension:

var newDt = dt.AsEnumerable()
              .GroupBy(r => r.Field<int>("Id"))
              .Select(g =>
              {
                  var row = dt.NewRow();

                  row["Id"] = g.Key;
                  row["Amount 1"] = g.Sum(r => r.Field<int>("Amount 1"));
                  row["Amount 2"] = g.Sum(r => r.Field<int>("Amount 2"));
                  row["Amount 3"] = g.Sum(r => r.Field<int>("Amount 3"));

                  return row;
              }).CopyToDataTable();

这篇关于使用Linq进行GroupBy和Sum数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆