前言:近期项目中有个小需求,就是要把一个数据源分成两部分,每5个分一份。下面代码资料来源于网络,经过修改加工后所得,已经用于实际开发
废话不多说,上代码
/// <summary> /// 分解数据表 /// </summary> /// <param name="originalTab">需要分解的表</param> /// <param name="rowsNum">每个表包含的数据量</param> /// <returns></returns> public static DataSet SplitDataTable(DataTable originalTab, int rowsNum) { if (originalTab == null || originalTab.Rows.Count < 1) { return null; } //获取所需创建的表数量 int tableNum = originalTab.Rows.Count / rowsNum; //获取数据余数 int remainder = originalTab.Rows.Count % rowsNum; DataSet ds = new DataSet(); //获取最后一个表的行数量 int lastRowsCount = 0; if (remainder == 0) { lastRowsCount = rowsNum; } else { lastRowsCount = remainder; } //如果只需要创建1个表,直接将原始表存入DataSet if (tableNum == 0) { ds.Tables.Add(originalTab.Copy()); } else { int totalTableCount = remainder > 0 ? tableNum + 1 : tableNum; DataTable[] tableSlice = new DataTable[totalTableCount]; //Save orginal columns into new table. for (int c = 0; c < totalTableCount; c++) { tableSlice[c] = new DataTable(); foreach (DataColumn dc in originalTab.Columns) { tableSlice[c].Columns.Add(dc.ColumnName, dc.DataType); } } //Import Rows for (int i = 0; i < totalTableCount; i++) { // if the current table is not the last one if (i != totalTableCount - 1) { for (int j = i * rowsNum; j < ((i + 1) * rowsNum); j++) { tableSlice[i].ImportRow(originalTab.Rows[j]); } } else { for (int k = i * rowsNum; k < (i * rowsNum + lastRowsCount); k++) { tableSlice[i].ImportRow(originalTab.Rows[k]); } } } //add all tables into a dataset foreach (DataTable dt in tableSlice) { ds.Tables.Add(dt); } } return ds; }
微信扫码查看本文
发表评论