【学习笔记】DataTable根据多列分组
今天遇到个问题,需要根据DataTable的两列来分组汇总数量,上网找了下资料,很快就找到大神已经帮忙解决了:-D,在此记下,以便查看~~
DataTable dataTable1 = new DataTable("BlogUser"); dataTable1.Columns.Add(new DataColumn("批号", typeof(String))); dataTable1.Columns.Add(new DataColumn("类型", typeof(String))); dataTable1.Columns.Add(new DataColumn("数量", typeof(Int32))); dataTable1.Rows.Add(new Object[] { "0001", "A", 100 }); dataTable1.Rows.Add(new Object[] { "0002", "B", 200 }); dataTable1.Rows.Add(new Object[] { "0001", "B", 300 }); dataTable1.Rows.Add(new Object[] { "0002", "B", 400 }); dataTable1.Rows.Add(new Object[] { "0003", "A", 500 }); DataView dv = dataTable1.DefaultView; DataTable dataTable2 = dv.ToTable(true, new string[] { "批号", "类型" }); String s = ""; for (int i = 0; i < dataTable2.Rows.Count; i++) { String pc = dataTable2.Rows[i][0].ToString(), type = dataTable2.Rows[i][1].ToString(); s += pc + "," + type + "=" + dataTable1.Compute("Sum(数量)", "批号='" + pc + "' AND 类型='" + type + "'").ToString() + Environment.NewLine; } Console.WriteLine(s);