日期:2014-05-18 浏览次数:20950 次
private DataTable InitTable() { DataTable dt = new DataTable(); dt.Columns.Add("no"); dt.Columns.Add("partno"); dt.Columns.Add("model"); return dt; } private void button1_Click(object sender, EventArgs e) { DataTable dt = this.InitTable(); DataRow dr; dr = dt.NewRow(); dr["no"] = "1"; dr["partno"] = "1_1"; dr["model"] = "pro"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["no"] = "2"; dr["partno"] = "2_1"; dr["model"] = "pro"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["no"] = "3"; dr["partno"] = "3_1"; dr["model"] = "pro1"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["no"] = "4"; dr["partno"] = "4_1"; dr["model"] = "pro1"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["no"] = "5"; dr["partno"] = "5_1"; dr["model"] = "pro2"; dt.Rows.Add(dr); //实现分组 IDictionary<string, DataTable> tables = new Dictionary<string, DataTable>(); foreach (DataRow r in dt.Rows) { string model = r["model"].ToString(); DataTable newTable; if (!tables.ContainsKey(model)) { newTable = this.InitTable(); tables.Add(model, newTable); } else { newTable = tables[model]; } DataRow newRow = newTable.NewRow(); for (int j = 0; j < dt.Columns.Count; j++) { newRow[j] = r[j]; } newTable.Rows.Add(newRow); } foreach (KeyValuePair<string, DataTable> keyAndValue in tables) { MessageBox.Show("model=" + keyAndValue.Key + "的表数据行数为:" + keyAndValue.Value.Rows.Count.ToString()); } }