【问题标题】:Datatable Group by and sum one column数据表分组并求和一列
【发布时间】:2016-05-10 08:29:27
【问题描述】:

我有这个数据表:

RadkyData.Columns.Add("ČísloDokladuDodavatele", typeof(string));
            RadkyData.Columns.Add("Množství", typeof(string));
            RadkyData.Columns.Add("NákupníCena", typeof(string));
            RadkyData.Columns.Add("PřepočtováJednotka", typeof(string));
            RadkyData.Columns.Add("Přepočtovýkoeficient", 

【问题讨论】:

  • AsEnumerable,但我有错误:AsEnumerable(System.Data.DataTable)' 是一个“方法”,在给定的上下文 C 中无效
  • 你试过给定的方法之一吗?

标签: c# datatable


【解决方案1】:

只需按Col1, Col2,Col3Sum() 向上Col4 对行进行分组

var input = new[] {
    new { Col1 =1, Col2= 2, Col3 = 1, Col4 = 1.5m},
    new { Col1 =1, Col2= 1, Col3 = 1, Col4 = 1.8m},
    new { Col1 =1, Col2= 2, Col3 = 1, Col4 = 2.5m},
    new { Col1 =1, Col2 =1, Col3 = 1, Col4 = 3m},
    new { Col1 =3, Col2 =1, Col3 = 4, Col4=  5m}
    };

var result = input.GroupBy(x => new { x.Col1, x.Col2, x.Col3 })
        .Select(x => new
        {
            Col1 = x.Key.Col1,
            Col2 = x.Key.Col2,
            Col3 = x.Key.Col3,
            Col4 = x.Sum(y => y.Col4)
        });

【讨论】:

    【解决方案2】:

    你可以使用Linq来做到这一点。

        table.AsEnumerable()
             .Select(r=>new 
                        {
                            c1=r.Field<int>("col1"), 
                            c2 =r.Field<int>("col2"), 
                            c3 =r.Field<int>("col3"), 
                            c4 =r.Field<double>("col4")  
                        })
             .GroupBy(g=> new {g.c1, g.c2, g.c3})
             .Select(x=> new {
                col1 = x.Key.c1,
                col2 = x.Key.c2,
                col3 = x.Key.c3,
                Sum = x.Sum(s=>s.c4)
            });
    

    查看Demo

    输出:

    { col1 = 1, col2 = 2, col3 = 1, Sum = 4 }
    { col1 = 1, col2 = 1, col3 = 1, Sum = 4.8 }
    { col1 = 3, col2 = 1, col3 = 4, Sum = 5 }
    

    【讨论】:

    • Sum = x.Sum(s=&gt;s.c4)
    • 谢谢,但我有问题...我还有其他列 Col5,Col6...但我只需要分组 col1-col4 并选择 Col5 和 6...从第一个...跨度>
    • 如果您不想从Select 语句中删除其他列,我们可以这样做。答案是根据您在问题中提供的信息编写的:-)。
    • 我需要选择所有列(在结果中)...Col1 - Col6,但只对 Col1-Col3 相同的 Col4 求和...
    • col1-3分组后col5或col6有多个值怎么办?如果你能回答这就是你想要的。
    【解决方案3】:

    我认为这应该可行 mytable.Columns.Add("col4",GetType(Integer),"Col1+Col2+Col3");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 2018-05-22
      • 1970-01-01
      • 2021-08-20
      • 2019-12-27
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多