我有数据表的列
transactionid,tenderid,amount,bankcode,CardType
我需要从transactionid,tenderid,Sum(amount),bankcode,CardType
transactionid,tenderid,bankcode,CardType
这是我所达到的,但我不知道我应该在选择
中输入什么 dttransactiontenders= dttransactiontenders.AsEnumerable()
.GroupBy(r => new { Col1 = r["transactionid"], Col2 = r["tenderid"], Col3 = r["bankcode"], Col4 = r["CardType"] })
.Select(g => g.OrderBy(r => r["transactionid"]).First())
.CopyToDataTable();
答案 0 :(得分:2)
由于您要计算总和,因此无法使用现有DataRows
,因此您必须创建新的。然后你不能使用CopyToDataTable
。相反,你可以使用这种方法:
DataTable dtResult = dttransactiontenders.Clone(); // same columns, empty
var query = dttransactiontenders.AsEnumerable()
.GroupBy(r => new { Col1 = r["transactionid"], Col2 = r["tenderid"], Col3 = r["bankcode"], Col4 = r["CardType"] });
foreach(var g in query)
{
DataRow addedRow = dtResult.Rows.Add();
addedRow["transactionid"] = g.Key.Col1;
addedRow["tenderid"] = g.Key.Col2;
addedRow["bankcode"] = g.Key.Col3;
addedRow["CardType"] = g.Key.Col4;
addedRow["amount"] = g.Sum(r => r.Field<int>("amount"));
}
如果您想覆盖旧的DataTable
,只需指定新的:
dttransactiontenders = dtResult;