Sunday 27 June 2021

split data table by rows c#

In this demo, large data table records split into multiple tables based on a given number of records.
For Example, 1000 records split into two tables if we pass a split table with 500 records in each table. Based on the number of records last table record may vary.

Datatable does not contain a definition for AsEnumerable: - Using NuGet Package Manager install the System.Data.DataTableExtensions 

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

class Program
{
    public static IEnumerable<IEnumerable<T>> Split<T>(IEnumerable<T> enumerable, int chunkSize)
    {
        int itemsReturned = 0;
        List<T> list = enumerable.ToList();
        int count = list.Count;
        while (itemsReturned < count)
        {
            int currentChunkSize = Math.Min(chunkSize, count - itemsReturned);
            yield return list.GetRange(itemsReturned, currentChunkSize);
            itemsReturned += currentChunkSize;
        }
    }
 
    static void Main(string[] args)
    {
        DataTable dt = new DataTable("Table1");
        dt.Columns.Add("Col1");
        dt.Columns.Add("Col2");
 
        DataRow dr = null;
 
        for (int i = 0; i < 3400; i++)
        {
            dr = dt.NewRow();
            dr["Col1"] = i + 1;
            dr["Col2"] = i + 1;
            dt.Rows.Add(dr);
        }
 
        var tables = Split(dt.AsEnumerable(), 500).Select(rows => rows.CopyToDataTable());
 
        foreach (DataTable item in tables)
        {
            //code goes here
        }
        Console.ReadLine();
    }
}
 
With Extension Method
 
public static class Helper
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> enumerable, int chunkSize)
    {
        int itemsReturned = 0;
        List<T> list = enumerable.ToList();
        int count = list.Count;
        while (itemsReturned < count)
        {
            int currentChunkSize = Math.Min(chunkSize, count - itemsReturned);
            yield return list.GetRange(itemsReturned, currentChunkSize);
            itemsReturned += currentChunkSize;
        }
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        DataTable dt = new DataTable("Table1");
        dt.Columns.Add("Col1");
        dt.Columns.Add("Col2");
 
        DataRow dr = null;
 
        for (int i = 0; i < 3400; i++)
        {
            dr = dt.NewRow();
            dr["Col1"] = i + 1;
            dr["Col2"] = i + 1;
            dt.Rows.Add(dr);
        }
 
        var tables = dt.AsEnumerable().Split(500).Select(rows => rows.CopyToDataTable());
 
        foreach (DataTable item in tables)
        {
            //code goes here
        }
        Console.ReadLine();
    } 
}

No comments:

Post a Comment