A simple way to use traversal to split a DataTable
Private StaticList<datatable> datatablesplite (DataTable DT,intmodcounts) {List<DataTable> list =NewList<datatable>(); intcounts = dt. rows.count/modcounts;///take an integer number of numbers intMoD = dt. Rows.Count% Modcounts;///remainder if(MoD >0) { intindex =0; ///the part that handles the split multiplier for(inti =0; I < counts; i++) {DataTable dt1=dt. Clone (); Dt1. TableName="Count"+i; for(intj = Index * modcounts; J < (Index +1) * modcounts; J + +) {DataRow NewRow=dt. NewRow (); DataRow Row1=dt. ROWS[J]; newrow["name"] = row1["name"]; newrow[" Age"] = row1[" Age"]; Dt1. Rows.Add (NewRow. ItemArray); } Index++; List. ADD (DT1); } ///the combination of the processing remainder partDataTable DT2 =dt. Clone (); DT2. TableName="modetable"; for(inti = counts * modcounts; i < dt. Rows.Count; i++) {DataRow NewRow=dt. NewRow (); DataRow Row1=dt. Rows[i]; newrow["name"] = row1["name"]; newrow[" Age"] = row1[" Age"]; DT2. Rows.Add (NewRow. ItemArray); } list. ADD (DT2); } Else { ///case with a remainder of 0 intindex =0; for(inti =0; I < counts; i++) {DataTable dt1=dt. Clone (); Dt1. TableName="modetable"; for(intj = Index * modcounts; J < (Index +1) * modcounts; J + +) {DataRow NewRow=dt. NewRow (); DataRow Row1=dt. ROWS[J]; newrow["name"] = row1["name"]; newrow[" Age"] = row1[" Age"]; Dt1. Rows.Add (NewRow. ItemArray); } Index++; List. ADD (DT1); } } returnlist; }
is easier to implement, and can be done in a way that uses LINQ
The code is as follows:
Private StaticList<datatable> DataTableSplite2 (DataTable DT,intmodcounts) { intcounts = dt. rows.count/modcounts;///take an integer number of numberslist<datatable> list =NewList<datatable> ();/// intindex =0; for(inti =0; I < counts +1; i++) {list. ADD (dt. AsEnumerable (). Skip (Index*modcounts). Take (modcounts). CopyToDataTable ()); Index++; } returnlist; }
Less code.
C # Universal DataTable split Small table