我需要将一个数据视图复制到一个数据表中。似乎唯一的方法是逐个遍历数据视图并复制到数据表中。一定有更好的方法。
dt = DataView.ToTable()
或者
dt = DataView.Table.Copy()
,
或者
dt = DataView.Table.Clone()
;
这个答案对我的情况不适用,因为我有带表达式的列。 DataView.ToTable()
只会复制值,而不是表达式。
首先我尝试了这个方法:
//clone the source table
DataTable filtered = dt.Clone();
//fill the clone with the filtered rows
foreach (DataRowView drv in dt.DefaultView)
{
filtered.Rows.Add(drv.Row.ItemArray);
}
dt = filtered;
但是那个解决方案非常缓慢,即使只有1000行。
对我有效的解决方案是:
//create a DataTable from the filtered DataView
DataTable filtered = dt.DefaultView.ToTable();
//loop through the columns of the source table and copy the expression to the new table
foreach (DataColumn dc in dt.Columns)
{
if (dc.Expression != "")
{
filtered.Columns[dc.ColumnName].Expression = dc.Expression;
}
}
dt = filtered;
DataView.ToTable()
只会复制 DataView 中的值。DataView.Table.Copy()
会复制源 DataTable,而不是 DataView 中过滤后的数据。DataView.Table.Clone()
仅会复制源 DataTable 的结构。 - Homer