我想将一个DataRow
数组转换成DataTable
...最简单的方法是什么?
针对 .Net Framework 3.5 及以上版本
DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();
但是,如果数组中没有行,它可能会导致错误,例如 The source contains no DataRows。因此,如果您决定使用此方法 CopyToDataTable()
,您应该检查数组以确定它是否具有数据行。
if (dr.Length > 0)
DataTable dt1 = dr.CopyToDataTable();
MSDN上提供了相关资料: DataTableExtensions.CopyToDataTable方法(IEnumerable)
foreach (DataRow row in rowArray) {
dataTable.ImportRow(row);
}
确保您的dataTable与DataRow数组中的DataRows具有相同的架构。
DataTable dataTable = new DataTable(); dataTable.ImportRow(dataRow); MyControl.DataSource = dataTable;
- humbadsrowArray.CopyToDataTable();
,因为它保留了表结构,而不是用新的表对象替换它! - Mojtaba RezaeianDataTable dt = new DataTable();
DataRow[] dr = (DataTable)dsData.Tables[0].Select("Some Criteria");
dt.Rows.Add(dr);
输入数组的长度超过了此表中的列数。
"。有克隆版本错误:"无法将类型为'System.Data.DataRow'的对象转换为类型'System.IConvertible'。无法将<System.Data.DataRow>存储在StoreOrder列中。预期类型是Int64.
" 注意:StoreOrder
是表模式中的第一列。看起来它正在试图将整个数据行压缩到第一列中。 - Brian Webster另一种方法是使用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");
简单的方法是:
// 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());
DataTable Assetdaterow =
(
from s in dtResourceTable.AsEnumerable()
where s.Field<DateTime>("Date") == Convert.ToDateTime(AssetDate)
select s
).CopyToDataTable();
DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{
dt.ImportRow(dr);
}
DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();
.Net 3.5+新增了DataTableExtensions,可以使用DataTableExtensions.CopyToDataTable方法。
对于datarow数组,只需使用.CopyToDataTable()即可返回datatable。
对于单个datarow使用
new DataRow[] { myDataRow }.CopyToDataTable()
You could use System.Linq like this:
if (dataRows != null && dataRows.Length > 0)
{
dataTable = dataRows.AsEnumerable().CopyToDataTable();
}
copyToDataTable()
?我在 .net 2.0 中没有找到它。 - SMUsamaShahcopyToDataTable()
方法创建了选定行列的完全副本,而datatable.ImportRow(row)
方法则没有,因此应将其标记为正确答案。 - Dante