具有相同ID的Sum列

时间:2017-06-04 13:22:55

标签: c# .net

我有两个数据表,我合并了它们。合并后,我想在datagrid中显示它们,但是如果有相同的'id'列应该是sum和group。

实施例; 目前它看起来像这样

enter image description here

如果'realid'列与下面相同,我想要的是求和;

enter image description here

我目前做了以下代码,最后我将它绑定到datagrid。

之后我该怎么办?

        DataTable dtNewTable = new DataTable();
        DataTable dtCurtable = new DataTable();

        private void Form1_Load(object sender, EventArgs e)
        {
            // Add columns
            DataColumn column2 = new DataColumn("counts", typeof(System.Int32));
            DataColumn column3 = new DataColumn("realid", typeof(string));
            dtNewTable.Columns.Add(column2);
            dtNewTable.Columns.Add(column3);


            dtCurtable = dtNewTable.Copy();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataRow row;
            Random r = new Random();

            dtNewTable.Clear();


            for (int i = 0; i <= 1; i++)
            {
                row = dtNewTable.NewRow();
                row["counts"] = r.Next(10,40) ;
                row["realid"] = i + " id";
                dtNewTable.Rows.Add(row);

            }

            dtCurtable.Merge(dtNewTable);
            dataGrid1.DataSource = dtCurtable;

        }

1 个答案:

答案 0 :(得分:0)

你可以在这里使用Linq

var dt1 = dtCurtable.AsEnumerable()
              .GroupBy(r => r.Field<string>("realid"))
              .Select(g =>
              {
              DataRow row = dtCurtable.NewRow();
              row["realid"] = g.Key;
              row["Count"] = g.Sum(r => r.Field<int>("counts"));


              return row;
          }).CopyToDataTable();