C#用DataTable实现Group by数据统计
时间:2021-05-24 05:33:05
收藏:0
阅读:0
1、用两层循环计算,前提条件是数据已经按分组的列排好序的。
1 DataTable dt = new DataTable(); 2 dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)), 3 new DataColumn("sex", typeof(string)), 4 new DataColumn("score", typeof(int)) }); 5 dt.Rows.Add(new object[] { "张三","男",1 }); 6 dt.Rows.Add(new object[] { "张三","男",4 }); 7 dt.Rows.Add(new object[] { "李四","男",100 }); 8 dt.Rows.Add(new object[] { "李四","女",90 }); 9 dt.Rows.Add(new object[] { "王五","女",77 }); 10 DataTable dtResult = dt.Clone(); 11 for (int i = 0; i < dt.Rows.Count; ) 12 { 13 DataRow dr = dtResult.NewRow(); 14 string name = dt.Rows[i]["name"].ToString(); 15 string sex = dt.Rows[i]["sex"].ToString(); 16 dr["name"] = name; 17 dr["sex"] = sex; 18 int score = 0; 19 //内层也是循环同一个表,当遇到不同的name时跳出内层循环 20 for (; i < dt.Rows.Count; ) 21 { 22 if (name == dt.Rows[i]["name"].ToString()&&name == dt.Rows[i]["sex"].ToString()) 23 { 24 score += Convert.ToInt32(dt.Rows[i]["score"]); 25 dr["score"] = score; 26 i++; 27 } 28 else 29 { 30 break; 31 } 32 } 33 dtResult.Rows.Add(dr); 34 } 35 36 dtResult中的数据即是最终结果。
2、 借助DataTable的Compute方法,DataTable中数据不用事先排好序。
1 DataTable dt = new DataTable(); 2 dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)), 3 new DataColumn("sex", typeof(string)), 4 new DataColumn("score", typeof(int)) }); 5 dt.Rows.Add(new object[] { "张三","男",1 }); 6 dt.Rows.Add(new object[] { "张三","男",4 }); 7 dt.Rows.Add(new object[] { "李四","男",100 }); 8 dt.Rows.Add(new object[] { "李四","女",90 }); 9 dt.Rows.Add(new object[] { "王五","女",77 }); 10 DataTable dtResult = dt.Clone(); 11 DataTable dtName = dt.DefaultView.ToTable(true, "name","sex"); 12 for (int i = 0; i < dtName.Rows.Count; i++) 13 { 14 DataRow[] rows = dt.Select("name=‘" + dtName.Rows[i][0] + "‘ and sex=‘" + dtName.Rows[i][1] + "‘"); 15 //temp用来存储筛选出来的数据 16 DataTable temp = dtResult.Clone(); 17 foreach (DataRow row in rows) 18 { 19 temp.Rows.Add(row.ItemArray); 20 } 21 22 DataRow dr = dtResult.NewRow(); 23 dr[0] = dtName.Rows[i][0].ToString(); 24 dr[1] = temp.Compute("sum(score)", ""); 25 dtResult.Rows.Add(dr); 26 }
3、使用linq to DataTable group by实现
var query = from t in dt.AsEnumerable() group t by new { t1 = t.Field<string>("name"), t2 = t.Field<string>("sex") } into m select new { name = m.Key.t1, sex = m.Key.t2, score = m.Sum(n => n.Field<decimal>("score")) }; if (query.ToList().Count > 0) { query.ToList().ForEach(q => { Console.WriteLine(q.name + "," + q.sex + "," + q.score); }); }
收集整理,非原创。转载:https://www.cnblogs.com/sydeveloper/archive/2013/03/29/2988669.html
评论(0)