DataView可以帮我们直接获取Distinct数据,
DataTable dataTable;DataView dataView = dataTable.DefaultView;
DataTable dataTableDistinct = dataView.ToTable(true,"FieldName1","FieldName2","...");
//注:其中ToTable()的第一个参数为是否DISTINCT
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()); //合计