C# – 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?


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

    foreach (DataRow row in drs)

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

    for(int i = 0; i < drs.Length; i++)

Best 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);