How to partitioning or splitting DataTable?

public static class DataExtensions
{
public static IEnumerable<IEnumerable> Partition(this DataTable dataTable, int partitionSize)
{
var numRows = Math.Ceiling((double)dataTable.Rows.Count);
for(var i = 0; i < numRows / partitionSize; i++)
{
yield return Partition(dataTable, i * partitionSize, i * partitionSize + partitionSize);
}
}
private static IEnumerable Partition(DataTable dataTable, int index, int endIndex)
{
for(var i = index; i < endIndex && i < dataTable.Rows.Count; i++)
{
yield return dataTable.Rows[i];
}
}
}
var partitions = dataTable.Partition(100);

dataTable.Skip(0).Take(100);
dataTable.Skip(100).Take(100);
dataTable.Skip(200).Take(100);
dataTable.Skip(300).Take(100);

Will iterate 0 times, and take 100 on the first execution. Then iterate through 100 rows, take 100, then iterate 200 rows, then take 100, etc.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s