DataTable MyTable = ds.Tables[2]; //ds为数据集
DataTable dtClone = MyTable.Clone(); //创建新表
DataView dv = new DataView(dtClone); //用于查找
dv.Sort = "Item";
foreach(DataRow dr in MyTable.Rows) //单循环, 效率高一点
{
int rowIndex = dv.FindRow(dr["Item"]);
if (rowIndex == -1)
{
dtClone.ImportRow(dr); //添加行
dtClone.Rows[dtClone.Rows - 1]
["Quantity"] = (decimal)MyTable.Compute("Sum(Quantity)", string.Format("Item = ‘{0}‘", dr["Item"].ToString());
//合计
}
}
dtClone.AcceptChanges();
ds.Tables.Remove(MyTable); //删除旧表
ds.Tables.Add(dtClone); //添加新表
dtClone.Rows[dtClone.Rows.Count - 1] ["Quantity"] = (decimal)MyTable.Compute("Sum(Quantity)", string.Format("Item = ‘{0}‘", dr["Item"].ToString()); //合计
原文:http://www.cnblogs.com/Unrmk-LingXing/p/4081957.html