Datatable Group by和sum一列

时间:2016-05-10 08:29:27

标签: c# datatable

我有这个数据表:

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", 

3 个答案:

答案 0 :(得分:0)

只需按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)
        });

答案 1 :(得分:0)

您可以使用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 }

答案 2 :(得分:0)

我认为这应该有效     mytable.Columns.Add( “COL4” 的GetType(整数), “Col1中+ + Col2中COL3”);