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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/769770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:27:36  来源:igfitidea点击:

Easiest way to copy a dataview to a datatable in C#?

c#datatabledataview

提问by Ravedave

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.

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

采纳答案by Jose Basilio

dt = DataView.ToTable()

OR

或者

dt = DataView.Table.Copy(),

dt = DataView.Table.Copy(),

OR

或者

dt = DataView.Table.Clone();

dt = DataView.Table.Clone();

回答by Homer

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;