2

I have data table with 100000 records, I want to iterate through data table for every 10,000 records I want to save the records. for the next iteration next 10000 records I want to save until for 100000 records.

DataTable dt = new DataTable();

dt = ds.tables[0];  //here i am getting 100,000 records

for (int i = 0; i < dt.rows.count; i + 10000)
{
    savedatatable(dt[i]);
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Tan
  • 778
  • 3
  • 18
  • 36

2 Answers2

2

You should use the following code:

DataTable dt = new DataTable();

dt = ds.tables[0];  //here i am getting 100,000 records

//Loop through columns in rows
for (int i = 0; i < dt.rows.count && i < 100000; i += 10000)
{
    foreach (DataColumn col in dt.Columns)
        savedatatable(dt.Rows[col.ColumnName].ToString());
}

or

DataTable dt = new DataTable();

dt = ds.tables[0];  //here i am getting 100,000 records

//Loop through rows in columns
foreach (DataColumn col in dt.Columns)
{
    for (int i = 0; i < dt.rows.count && i < 100000; i += 10000)
        savedatatable(dt.Rows[col.ColumnName].ToString());
}

Here's a similar question, but I'm not sure if this is what you wanted. : Looping through a DataTable

Community
  • 1
  • 1
J3soon
  • 3,013
  • 2
  • 29
  • 49
1

Should be something like this:

for (int i = 0; i < dt.Rows.Count; i+=10000)
{
    DataRow dr = dt.Rows[i];
    // do something
} 
AsfK
  • 3,328
  • 4
  • 36
  • 73
  • The first comment is unnecessary since you have already checked `i`'s value with `i < dt.Rows.Count`. – J3soon Mar 20 '16 at 10:57
  • @J3soon, just if you sure your rows count % 10000 = 0. otherwise your index can be out of range. – AsfK Mar 20 '16 at 12:27
  • Since the `i+=10000` is called after the `body`, it'll be fine to leave the `i < dt.Rows.Count` there. It'll be checked at the start of the `body`, so the comment is unnecessary. Please see [for](https://msdn.microsoft.com/library/ch45axte.aspx). – J3soon Mar 20 '16 at 12:41
  • 1
    You're totally right, thanks for the lesson ! I'll remove the comment – AsfK Mar 20 '16 at 14:39
  • second time when the loop executes the i value will be 20000, but if i want to skip the first 10,000 and get the next 10,000 how to do it – Tan Mar 20 '16 at 17:53
  • @Tan, if I got you right, you want to start from record #20,000. Therefore in the if statement you can define `int i = 20000` – AsfK Mar 22 '16 at 08:05