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

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

问题描述

我有一个这样的数据表:

<前>编号 金额 1 金额 2 金额 31 2 2 212 4 6 412 6 6 522 7 2 122 7 2 2

我需要像这样获取我的数据表:

<前>编号 金额 1 金额 2 金额 31 2 2 212 10 12 922 14 4 3

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

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

这段代码肯定不会编译,但如果可能的话,任何帮助/建议都会非常感激.我对 linq 很陌生.

解决方案

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

var newDt = dt.AsEnumerable().GroupBy(r => r.Field("Id")).Select(g =>{var row = dt.NewRow();row["Id"] = g.Key;row["金额 1"] = g.Sum(r => r.Field("金额 1"));row[金额 2"] = g.Sum(r => r.Field(金额 2"));row[金额 3"] = g.Sum(r => r.Field(金额 3"));返回行;}).CopyToDataTable();

Hi, I have a Datatable like this:

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

I need to get my datatable like this:

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();

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

解决方案

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天全站免登陆