Search code examples
c#asp.netforeachsplitdatatable

Get tables from splitted datatable and run a foreach for every table


I need to get all tables created when splitting a datatable and the run a foreach onevery row on every table that has been created with the split

This is the code i am using to split the datatable

                using (DataTable dt = new DataTable())

            using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
            {
                adapter.Fill(dt);
                //return dt;

                DataTable[] dt1 = dt.AsEnumerable()
                .Select((row, index) => new { row, index })
                .GroupBy(x => x.index / 9999)  // integer division, the fractional part is truncated
                .Select(g => g.Select(x => x.row).CopyToDataTable())
                .ToArray();

                Foreach (DataSet in dt1){ }

Solution

  • You can iterate over the array of DataTables using foreach, and then iterate over the rows of each DataTable using another foreach:

    using System;
    using System.Data;
                        
    public class Program
    {
        public static void Main()
        {
            //building the array of DataTables
            DataTable dt1 = new DataTable();
            DataTable dt2 = new DataTable();
            DataTable[] dtArray = new DataTable[2];
            dtArray[0] = dt1;
            dtArray[1] = dt2;
            
            //iterate over array
            foreach(DataTable datatb in dtArray) {
                
                //iterate over rows in individual DataTable
                foreach(DataRow dr in datatb.Rows) {
                     //get column data from row
                     var test = dr["columnName"].ToString();
                }
            }
        }
    }
    

    You can see how to iterate over columns in each row of a DataTable here