对DataTable中相等的数据求和,然后将它们传递给新的DataTable C#

时间:2019-02-21 23:09:29

标签: c# linq datatable

我有一个SELECT查询:

SELECT * FROM XXXXX

恢复后,我将其保存在DataTable中,假设此DataTable看起来像这样(表格的反映):

code       description     amount     unit    prize
----------------------------------------------------
0001          papaya        100,5      KG      75
0002          mango          50        KG      50
0001          papaya        200,5      KG      75

如果它们具有相同的代码,我该如何遍历数据表并将所有“金额”相加并将其传递给新的数据表?

code        description          amount     unit    prize
----------------------------------------------------------
0001          papaya               301      KG         75
0002          mango                 50      KG         50

我尝试过类似的方法,但是我有点迷失了(我认为这不是正确的方法):

var query = from row in dt.AsEnumerable()
            group row by row.Field<string>("code") into g
            select new 
                   {
                        cod_parte = g.Key,
                        descripcion = g.First().GetChildRows("descripcion").ToString(),
                        cantidad = g.Sum(x => x.Field<int>("cantidad")),
                        unidad = g.First().GetChildRows("unidad").ToString(),
                        precio = Convert.ToDouble(g.First().GetChildRows("precio"))
                   };

DataTable dtResult = new DataTable();
dtResult = query.CopyToDataTable();

2 个答案:

答案 0 :(得分:1)

使用System.Linq可以轻松实现

使用上面的数据表示例,您应该首先按代码分组,然后为分组中的每个元素选择一个具有键和总和的新对象。

这可以通过以下代码实现

// Fill our list
var list = new List<Item>
{
    new Item {Code = 1, Price = 2},
    new Item {Code = 2, Price = 2},
    new Item {Code = 1, Price = 2}
};

// Perform LINQ
var result = list.GroupBy(x => x.Code).Select(x => new
{
    Code = x.Key,
    Sum = x.Sum(z => z.Price)
}).ToList();

或者按照您的数据表示例操作(我的西班牙语不是100%)

var query = dt.AsEnumerable().GroupBy(x => x.Field<string>("code")).Select(x => new
{
    cod_parte = x.Key,
    cantidad = x.Sum(z => z.Field<int>("cantidad")),
}).ToList();

答案 1 :(得分:1)

您可以执行以下操作:

DataTable table = new DataTable();
        table.Columns.Add("Code", typeof(string));
        table.Columns.Add("Description", typeof(string));
        table.Columns.Add("Amount", typeof(int));
        table.Columns.Add("Unit", typeof(string));
        table.Columns.Add("Prize", typeof(double));

        // Here we add five DataRows.
        table.Rows.Add("0001", "papaya", "100", "KG", 75);
        table.Rows.Add("0002", "mango", "50", "KG", 50);
        table.Rows.Add("0001", "papaya", "200", "KG", 75);

        var rows = table.AsEnumerable().GroupBy(row => row.Field<string>("Code")).Select(g =>
        {
            var row = table.NewRow();

            row["Code"] = g.Key;
            row["Description"] = row.Field<string>("Description");
            row["Amount"] = g.Sum(y => y.Field<int>("Amount"));
            row["Unit"] = row.Field<string>("Unit");
            row["Prize"] = row.Field<double?>("Prize") == null ? 0 : row.Field<double>("Prize");
            return row;
        }).CopyToDataTable();

        foreach (var data1 in rows.Rows)
        {
            Console.WriteLine(data1.ToString());
        }