One of the requirements that came in was to split a large datatable into smaller ones defined by a batch size (say 2000). The below mentioned sample code helps to achieve this easily.
The given below method is used to create a large amount of sample data:
static DataTable GetTonsOfData()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
for (int i = 1; i <= 20000; i++)
{
DataRow Row = dt.NewRow();
Row["ID"] = i;
Row["Name"] = "Name " + i.ToString();
dt.Rows.Add(Row);
}
return dt;
}
The given below SplitTable method actually splits the original datatable into smaller datatables and insert them into a list of datatable.
private static List<DataTable> SplitTable(DataTable originalTable, int batchSize)
{
List<DataTable> tables = new List<DataTable>();
int i = 0;
int j = 1;
DataTable newDt = originalTable.Clone();
newDt.TableName = "Table_" + j;
newDt.Clear();
foreach (DataRow row in originalTable.Rows)
{
DataRow newRow = newDt.NewRow();
newRow.ItemArray = row.ItemArray;
newDt.Rows.Add(newRow);
i++;
if (i == batchSize)
{
tables.Add(newDt);
j++;
newDt = originalTable.Clone();
newDt.TableName = "Table_" + j;
newDt.Clear();
i = 0;
}
}
return tables;
}
DataTable dtFull = GetTonsOfData();
List<DataTable> splitdt = SplitTable(dtFull, 2000);
The code can be optimized if LINQ is implemented.
Yogesh UpretiPosted Sep 20, 2018, 8:10 AM
Thanks buddy
Sushi BurritoPosted Jan 20, 2017, 10:06 AM
You should really consider updating your example with the code provided by Dinesh. Why: If you pass in 2999 records, 999 records will be not be added to your tables output.
Madhusmita PadhiaryPosted Dec 4, 2014, 8:04 AM
Thank u dinesh ,the above code exactly dividing the datatable according to batch size,but it is deducting the rest value. But your code if the datatable is less than batch size it is also adding into split table.
Dinesh JethoePosted Oct 3, 2014, 3:21 PM
Nice Joxin Stanly, there are some points I could not get from the code so I've modified it a bit. Here are the modifications: internal static List<DataTable> SplitTable(DataTable originalTable, int batchSize) { List<DataTable> tables = new List<DataTable>(); DataTable new_table = new DataTable(); new_table = originalTable.Clone(); int j = 0; int k = 0; if (originalTable.Rows.Count <= batchSize) { new_table.TableName = "Table_" + k; new_table = originalTable.Copy(); tables.Add(new_table.Copy()); } else { for (int i = 0; i < originalTable.Rows.Count; i++) { new_table.NewRow(); new_table.ImportRow(originalTable.Rows[i]); if ((i + 1) == originalTable.Rows.Count) { new_table.TableName = "Table_" + k; tables.Add(new_table.Copy()); new_table.Rows.Clear(); k++; } else if (++j == batchSize) { new_table.TableName = "Table_" + k; tables.Add(new_table.Copy()); new_table.Rows.Clear(); k++; j = 0; } } } return tables; }
AgithraPosted Aug 7, 2014, 2:22 PM
It works. Thanks a lot.