问题描述:

I have a data table which has 1000 rows. one field is ID. count of distinct ID is 500. There is also a money column. I have to create a datatable where will be 500 rows. I think you can guess which 500. yes, for each distinct id, i have to sum all amount. Thats all.

The Datatable i have:

ID | Money

----------------

1 | 120

2 | 75

1 | 300

2 | 545

The Datatable I want:

ID | Money

----------------

1 | 420

2 | 620

网友答案:
  DataTable dt = new DataTable();
  dt.Columns.Add("ID");
  dt.Columns.Add("Money", typeof(double));
  DataTable dt2 = new DataTable();
  dt2.Columns.Add("ID");
  dt2.Columns.Add("Money", typeof(double));
  dt.Rows.Add("1", 20.50);
  dt.Rows.Add("1", 20.50);
  dt.Rows.Add("2", 15.30);
  dt.Rows.Add("2", 10.70);

  var rows = dt.Rows.Cast<DataRow>().GroupBy(x => x["ID"]).Select(x => new { ID = x.Key, Money = x.Sum(row => row.Field<double>("Money")) });
  foreach (var row in rows)
  {
    dt2.Rows.Add(row.ID, row.Money);
  }
网友答案:

Why not actually calculate from the database with SQL query? With some stored procedure in MS SQL Server or something... I think it's more robust and faster.

Something like this....

SELECT ID, Money, SUM(Money)
FROM theTable  
GROUP BY ID, Money
相关阅读:
Top