日期:2014-05-17 浏览次数:20915 次
DataTable dt2 = dt1.Copy(); dt2.Clear(); int age = 0; int money = 0; for (int i = 0; i < dt1.Rows.Count; i++) { if (i < 3) dt2.Rows.Add(dt1.Rows[i]); else { age += int.Parse(dt1.Rows[i]["age"].ToString()); money += int.Parse(dt1.Rows[i]["money"].ToString()); } } DataRow dr2 = dt2.NewRow(); dr2["id"] = 4; dr2["name"] = "其它"; dr2["age"] = age; dr2["money"] = money; dt2.Rows.Add(dr2);
------解决方案--------------------
DataTable dt = CreateDataTable();//得到你的datatable var result= dt.AsEnumerable().Where((a, index) => index >= dt.Rows.Count - 2).CopyToDataTable<DataRow>(); dt = dt.AsEnumerable().Where((a, index) => index < dt.Rows.Count - 2).CopyToDataTable<DataRow>(); DataRow dr = dt.NewRow(); dr["ID"] = dt.AsEnumerable().Last().Field<int>("ID") + 1; dr["name"] = "其他"; dr["age"] = result.Compute("sum(age)",null); dr["money"] = result.Compute("sum(money)", null); ; dt.Rows.Add(dr); //此时dt已符合要求
------解决方案--------------------
DataTable dt = new DataTable(); dt.Columns.Add("id", typeof(int)); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("age", typeof(int)); dt.Columns.Add("money", typeof(int)); dt.Rows.Add(1, "张一", 10, 10); dt.Rows.Add(2, "张二", 15, 20); dt.Rows.Add(3, "张三", 20, 30); dt.Rows.Add(4, "张四", 18, 40); dt.Rows.Add(5, "张五", 25, 50); int ageSum = (int)dt.Rows[dt.Rows.Count - 2]["age"] + (int)dt.Rows[dt.Rows.Count - 1]["age"]; int moneySum = (int)dt.Rows[dt.Rows.Count - 2]["money"] + (int)dt.Rows[dt.Rows.Count - 1]["money"]; dt.Rows.RemoveAt(dt.Rows.Count - 1); dt.Rows[dt.Rows.Count - 1]["name"] = "其他"; dt.Rows[dt.Rows.Count - 1]["age"] = ageSum; dt.Rows[dt.Rows.Count - 1]["money"] = moneySum;