C# – Simple way to convert datarow array to datatable

arrayscdatarowdatatable

I want to convert a DataRow array into DataTable … What is the simplest way to do this?

Best Answer

For .Net Framework 3.5+

DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();

But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.

if (dr.Length > 0)
    DataTable dt1 = dr.CopyToDataTable();

Reference available at MSDN: DataTableExtensions.CopyToDataTable Method (IEnumerable)