在C#中将一个DataView复制到一个DataTable的最简单方法是什么?

21

我需要将一个数据视图复制到一个数据表中。似乎唯一的方法是逐个遍历数据视图并复制到数据表中。一定有更好的方法。

2个回答

62
dt = DataView.ToTable()

或者

dt = DataView.Table.Copy(),

或者

dt = DataView.Table.Clone();


1
谢谢,谷歌的表现相当糟糕。希望这个页面能够排名靠前。 - Ravedave
11
注意:DataView.ToTable() 只会复制 DataView 中的值。DataView.Table.Copy() 会复制源 DataTable,而不是 DataView 中过滤后的数据。DataView.Table.Clone() 仅会复制源 DataTable 的结构。 - Homer

3

这个答案对我的情况不适用,因为我有带表达式的列。 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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接