将数据视图复制到C#中的数据表的最简单方法是什么?

时间:2022-12-02 14:04:13

I need to copy a dataview into a datatable. It seems like the only way to do so is to iterate through the dataview item by item and copy over to a datatable. There has to be a better way.

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

2 个解决方案

#1


dt = DataView.ToTable()

OR

dt = DataView.Table.Copy(),

dt = DataView.Table.Copy(),

OR

dt = DataView.Table.Clone();

dt = DataView.Table.Clone();

#2


The answer does not work for my situation because I have columns with expressions. DataView.ToTable() will only copy the values, not the expressions.

答案对我的情况不起作用,因为我有表达式的列。 DataView.ToTable()只会复制值,而不是表达式。

First I tried this:

首先我尝试了这个:

//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;

but that solution was very slow, even for just 1000 rows.

但是这个解决方案非常慢,即使只有1000行。

The solution that worked for me is:

对我有用的解决方案是:

//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;

#1


dt = DataView.ToTable()

OR

dt = DataView.Table.Copy(),

dt = DataView.Table.Copy(),

OR

dt = DataView.Table.Clone();

dt = DataView.Table.Clone();

#2


The answer does not work for my situation because I have columns with expressions. DataView.ToTable() will only copy the values, not the expressions.

答案对我的情况不起作用,因为我有表达式的列。 DataView.ToTable()只会复制值,而不是表达式。

First I tried this:

首先我尝试了这个:

//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;

but that solution was very slow, even for just 1000 rows.

但是这个解决方案非常慢,即使只有1000行。

The solution that worked for me is:

对我有用的解决方案是:

//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;