Saqib Lodhi
Saqib Lodhi

Reputation: 51

Break datatable into multiple tables by columns not rows

I have a datatable having columns like below

enter image description here

I want to break datatable into multiple datatables by splitting columns with every group of 4 columns like below

enter image description here

I can do it by simply by using loops and some calculations but wanted to get a better way if someone have.

Upvotes: 1

Views: 49

Answers (1)

Ctznkane525
Ctznkane525

Reputation: 7465

DataTable has a copy method, you could use that, and remove the columns you don't need.

https://msdn.microsoft.com/en-us/library/system.data.datatable.copy(v=vs.110).aspx

        System.Data.DataTable tbl = new System.Data.DataTable();
        // Add Dummy Columns
        for (int i = 0; i <= 11; i++)
        {
            tbl.Columns.Add(i.ToString());
        }

        // Assume We Have Data

        // Split Table Into Lists of Tables
        List <System.Data.DataTable> tables = new List<System.Data.DataTable>();
        for ( int i = 0; i <= 2; i++)
        {
            int firstColumn = i * 4;
            int lastColumn = i * 4 + 3;
            System.Data.DataTable tblCopy = tbl.Copy();
            for ( int j = 0; j < tbl.Columns.Count; j++)
            {
                if (j < firstColumn || j > lastColumn)
                    tblCopy.Columns.Remove(tbl.Columns[j].ColumnName);
            }

            tables.Add(tblCopy);
        }

Upvotes: 1

Related Questions