title: Enumerating Datatable rows in batches efficiently
body: <p>I'd like to enumerate through a datatable in batches. To do so, I've created a method which returns an <code>IEnumerable&lt;DataTable&gt;</code> That method looks like this:</p>
  
  <pre><code>public IEnumerable&lt;DataTable&gt; EnumerateRowsInBatches( DataTable table, int batchSize ) {
  
      int rowCount = table.Rows.Count;
      int batchIndex = 0;
      while( batchIndex * batchSize &lt; rowCount ) {
          DataTable result = table.Clone();
          int batchStart = batchIndex * batchSize;
          int batchLimit = ( batchIndex + 1 ) * batchSize;
          if( rowCount &lt; batchLimit )
              batchLimit = rowCount;
          for( int i = batchStart; i &lt; batchLimit; i++ ) {
              result.ImportRow( table.Rows[ i ] );
          }
          batchIndex++;
          yield return result;
      }
  }
  </code></pre>
  
  <p>This works pretty nicely actually. I'm iterating through these batches in order to send to SQL Server using a Table Valued Parameter. but I'm seeing that the <code>ImportRow</code> is taking the majority of the elapsed time and I'd like to speed it up. </p>
  
  <p>I'm looking for how to do that. I'm free to treat all data as read-only and so I get the sense that copying rows is not strictly necessary here.</p>