This article was reproduced from: http://www.cnblogs.com/sydeveloper/archive/2013/03/29/2988669.html
1, with two-layer cycle calculation, the precondition is that the data has been grouped by the column of the order.
DataTable dt =NewDataTable ();d T. Columns.addrange (NewDatacolumn[] {NewDataColumn ("name",typeof(string)), NewDataColumn ("Sex",typeof(string)), NewDataColumn ("score",typeof(int) });d T. Rows.Add (New Object[] {"Zhang San","male",1});d T. Rows.Add (New Object[] {"Zhang San","male",4});d T. Rows.Add (New Object[] {"John Doe","male", -});d T. Rows.Add (New Object[] {"John Doe","female", -});d T. Rows.Add (New Object[] {"Harry","female", the});D atatable dtresult=dt. Clone (); for(inti =0; I <dt. Rows.Count; ) {DataRow Dr=Dtresult.newrow (); stringname = dt. rows[i]["name"]. ToString (); stringsex = dt. rows[i]["Sex"]. ToString (); dr["name"] =name; dr["Sex"] =sex; intScore =0; //the inner layer also loops the same table and jumps out of the inner loop when different name is encountered 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);}
The data in Dtresult is the final result.
2, using the Compute method of the DataTable, the data in the DataTable is not ordered in advance.
DataTable dt =NewDataTable ();d T. Columns.addrange (NewDatacolumn[] {NewDataColumn ("name",typeof(string)), NewDataColumn ("Sex",typeof(string)), NewDataColumn ("score",typeof(int) });d T. Rows.Add (New Object[] {"Zhang San","male",1});d T. Rows.Add (New Object[] {"Zhang San","male",4});d T. Rows.Add (New Object[] {"John Doe","male", -});d T. Rows.Add (New Object[] {"John Doe","female", -});d T. Rows.Add (New Object[] {"Harry","female", the});D atatable dtresult=dt. Clone ();D atatable dtname= dt. Defaultview.totable (true,"name","Sex"); for(inti =0; i < DtName.Rows.Count; i++) {datarow[] rows= dt. Select ("name= '"+ dtname.rows[i][0] +"' and sex= '"+ dtname.rows[i][1] +"'"); //temp is used to store filtered data .DataTable temp =Dtresult.clone (); foreach(DataRow rowinchrows) {Temp. Rows.Add (row. ItemArray); } DataRow Dr=Dtresult.newrow (); dr[0] = dtname.rows[i][0]. ToString (); dr[1] = Temp.compute ("sum (Score)",""); DTRESULT.ROWS.ADD (DR);} 3, using the LINQ to DataTable Group by implementationvarquery = fromTinchdt. AsEnumerable () group T byNew{T1 = t.field<string> ("name"), t2 = t.field<string> ("Sex")} into MSelect 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); });}
Go C # using LINQ to implement group by data statistics for a DataTable