首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

DataSet中DataTable重复行删除和求和有关问题

2012-01-22 
DataSet中DataTable重复行删除和求和问题我从2个不同的数据库(Oralce和MSSQL)里查询得到1个数据集的2个表

DataSet中DataTable重复行删除和求和问题
我从2个不同的数据库(Oralce和MS   SQL)里查询得到1个数据集的2个表
我把这个数据集的2个表合并在一起得到一个新表,现在这个新表的结构是这样的:
DataTable   MyTable   =   ds.Tables[2];   //ds为数据集
Item       Description                         Uom     Quantity
a1           a1 's   description               EA       10.22  
a2           a2 's   description               EA       11.00  
a3           a3 's   description               KG       25.00  
a4           a4 's   description               KG       0.23  
a5           a5 's   description               KG       1.00
a1           a1 's   description               EA       0.25
a1           a1 's   description               EA       56.55  
a3           a3 's   description               KG       23.65
a4           a4 's   description               KG       25.36
我现在想把这个MyTable中字段Item重复行去掉,但是又要把Quantity的和加起来
即将MyTable变为(或者填充到ds的另一个表使变为):
Item       Description                         Uom     Quantity
a1           a1 's   description               EA       67.02     \\(10.22   +   0.25   +   56.55)
a2           a2 's   description               EA       11.00      
a3           a3 's   description               KG       48.65       \\(25.00   +   23.65)
a4           a4 's   description               KG       25.59           \\(0.23   +   25.36)
a5           a5 's   description               KG       1.00        

请哪位高手帮忙解决下,不胜感激!

[解决办法]
一定有这样看来只有遍历表,对比计算了,将生成的结果放到 一个DataTable里面去,用这个DataTable 来做数据源绑定
[解决办法]
for(int i=0;i <ds.Tables[ "T1 "].Rows.Count;i++)
{
object tempitem=ds.Tables[ "T1 "].Rows[i][0];
for(int j=i;j <ds.Tables[ "T1 "].Rows.Count;j++)
{
if(tempitem == ds.Tables[ "T1 "].Rows[j][0])
{
ds.Tables[ "T1 "].Rows[i][3] = (int)ds.Tables[ "T1 "].Rows[i][3] + (int)ds.Tables[ "T1 "].Rows[j][3];
ds.Tables[ "T1 "].Rows.RemoveAt(j);
}
}
}



=========================
不知道会出错没。
没测试。
[解决办法]
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(MyTable.Rows[i]);
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);
==
随手写了一下 没测试

热点排行