Search code examples
c#datatabledatarowcollection

How to get columns from a datarow?


I have a row collection (DataRow[] rows). And I want to import all rows to another DataTable (DataTable dt).

But how?

Code

DataTable dt;
if (drs.Length>0)
{
    dt = new DataTable();

    foreach (DataRow row in drs)
    {
        dt.Columns.Add(row???????)
    }

    // If it possible, something like that => dt.Columns.AddRange(????????)

    for(int i = 0; i < drs.Length; i++)
    {
        dt.ImportRow(drs[i]);
    }
}

Solution

  • Assuming the rows all have the same structure, the easiest option is to clone the old table, omitting the data:

    DataTable dt = drs[0].Table.Clone();
    

    Alternatively, something like:

    foreach(DataColumn col in drs[0].Table.Columns)
    {
        dt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
    }