GROUP by 方法 C#
1、用两层循环计算,前提条件是数据已经按分组的列排好序的。
DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)), new DataColumn("sex", typeof(string)), new DataColumn("score", typeof(int)) }); dt.Rows.Add(new object[] { "张三","男",1 }); dt.Rows.Add(new object[] { "张三","男",4 }); dt.Rows.Add(new object[] { "李四","男",100 }); dt.Rows.Add(new object[] { "李四","女",90 }); dt.Rows.Add(new object[] { "王五","女",77 }); DataTable dtResult = dt.Clone(); for (int i = 0; i < dt.Rows.Count; ) { DataRow dr = dtResult.NewRow(); string name = dt.Rows[i]["name"].ToString(); string sex = dt.Rows[i]["sex"].ToString(); dr["name"] = name; dr["sex"] = sex; int score = 0; //内层也是循环同一个表,当遇到不同的name时跳出内层循环 for (; i < dt.Rows.Count; ) { if (name == dt.Rows[i]["name"].ToString()&&name == dt.Rows[i]["sex"].ToString()) { score += Convert.ToInt32(dt.Rows[i]["score"]); dr["score"] = score; i++; } else { break; } } dtResult.Rows.Add(dr);
}
dtResult中的数据即是最终结果。
2、 借助DataTable的Compute方法,DataTable中数据不用事先排好序。
DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)), new DataColumn("sex", typeof(string)), new DataColumn("score", typeof(int)) }); dt.Rows.Add(new object[] { "张三","男",1 }); dt.Rows.Add(new