Simple way to convert datarow array to datatable

2019-01-21 05:12发布

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

13条回答
别忘想泡老子
2楼-- · 2019-01-21 05:50

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)

查看更多
看我几分像从前
3楼-- · 2019-01-21 05:55
DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
 DataRow AddNewRow = dataTable.AddNewRow();
 AddNewRow.ItemArray = dr.ItemArray;
 dataTable.Rows.Add(AddNewRow);
}
查看更多
淡お忘
4楼-- · 2019-01-21 05:56
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();
查看更多
疯言疯语
5楼-- · 2019-01-21 05:57

Another way is to use a DataView

// Create a DataTable
DataTable table = new DataTable()
...

// Filter and Sort expressions
string expression = "[Birth Year] >= 1983"; 
string sortOrder = "[Birth Year] ASC";

// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);

// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");
查看更多
【Aperson】
6楼-- · 2019-01-21 05:58

Why not iterate through your DataRow array and add (using DataRow.ImportRow, if necessary, to get a copy of the DataRow), something like:

foreach (DataRow row in rowArray) {
   dataTable.ImportRow(row);
}

Make sure your dataTable has the same schema as the DataRows in your DataRow array.

查看更多
放我归山
7楼-- · 2019-01-21 05:58

Simple way is:

// dtData is DataTable that contain data
DataTable dt = dtData.Select("Condition=1").CopyToDataTable();

// or existing typed DataTable dt
dt.Merge(dtData.Select("Condition=1").CopyToDataTable());
查看更多
登录 后发表回答