日期:2014-05-18  浏览次数:21385 次

DataTable进行汇总
例如:
批号 数量
0001 100
0002 200
0001 300
0002 400
0003 500
在DataTable中显示是这样的结果,现在在DataTable中根据批号汇总数量,怎么写?是C#程序编写啊!
我知道DataTable中两个方法Select()和Compute(),请各位指教一下。谢谢。

------解决方案--------------------
sumObject = DataTable.Compute("Sum(数量)", "批号='001'");
------解决方案--------------------
dataTable1是你的数据,那么就执行下面的

System.Data.DataView dv = dataTable1.DefaultView;
System.Data.DataTable dataTable2 = dv.ToTable(true, "批号");
for (int i = 0; i < dataTable2.Rows.Count; i++)
{
 String type = dataTable2.Rows[i][0].ToString();
 MessageBox.Show(type + "=" + dataTable1.Compute("Sum(数量)", "批号='" + type + "'").ToString());
}

就可以了

完整的例子
C# code
System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser");
System.Data.DataRow dr;
dataTable1.Columns.Add(new System.Data.DataColumn("批号", typeof(System.String)));
dataTable1.Columns.Add(new System.Data.DataColumn("数量", typeof(System.Int32)));
dataTable1.Rows.Add(new Object[] { "0001", 100 });
dataTable1.Rows.Add(new Object[] { "0002", 200 });
dataTable1.Rows.Add(new Object[] { "0001", 300 });
dataTable1.Rows.Add(new Object[] { "0002", 400 });
dataTable1.Rows.Add(new Object[] { "0003", 500 });
System.Data.DataView dv = dataTable1.DefaultView;
System.Data.DataTable dataTable2 = dv.ToTable(true, "批号");
String s = "";
for (int i = 0; i < dataTable2.Rows.Count; i++)
{
  String type = dataTable2.Rows[i][0].ToString();
  s += type + "=" + dataTable1.Compute("Sum(数量)", "批号='" + type + "'").ToString() + Environment.NewLine;
}
MessageBox.Show(s);