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

发布于 2024-07-17 05:18:17 字数 60 浏览 1 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橙味迷妹 2024-07-24 05:18:17
dt = DataView.ToTable()

dt = DataView.Table.Copy(),

dt = DataView.Table.Clone();

dt = DataView.ToTable()

OR

dt = DataView.Table.Copy(),

OR

dt = DataView.Table.Clone();

小清晰的声音 2024-07-24 05:18:17

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

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

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.

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文