C# 复制或克隆 DataRow 的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12025012/
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-09 20:06:54  来源:igfitidea点击:

Simple way to copy or clone a DataRow?

c#datatabledatarow

提问by Paul Matthews

I'm looking for a simple way to make a clone of a DataRow. Kind of like taking a snapshot of that Row and saving it. The values of original Row are then free to change but we still have another saved copy which doesn't change. Is this the correct way to do it?

我正在寻找一种简单的方法来克隆 DataRow。有点像拍摄该行的快照并保存它。然后原始 Row 的值可以自由更改,但我们仍然有另一个不会更改的已保存副本。这是正确的方法吗?

DataRow Source, Destination;
// Assume we create some columns and fill them with values
Destination.ItemArray = Source.ItemArray;

Will this just set Snapshot's ItemArray reference to point to the one in Source or does it actually make a separate copy? Should I do this instead?

这只是将 Snapshot 的 ItemArray 引用设置为指向 Source 中的那个引用还是它实际上制作了一个单独的副本?我应该这样做吗?

Destination.ItemArray = Source.ItemArray.Clone();

EDIT: I don't think the second code snippet actually compiles.

编辑:我认为第二个代码片段实际上没有编译。

采纳答案by cuongle

You can use ImportRowmethodto copy Row from DataTable to DataTable with the same schema:

您可以使用ImportRow方法将 Row 从 DataTable 复制到具有相同架构的 DataTable:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

更新:

With your new Edit, I believe:

有了你的新编辑,我相信:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

将工作

回答by rdjabarov

But to make sure that your new row is accessible in the new table, you need to close the table:

但是为了确保您的新行可以在新表中访问,您需要关闭该表:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

回答by mklement0

Note: cuongle's helfpul answerhas all the ingredients, but the solution can be streamlined (no need for .ItemArray) and can be reframed to better match the question as asked.

注意:cuongle 的 helfpul 答案包含所有要素,但可以简化解决方案(不需要.ItemArray)并且可以重新构建以更好地匹配所提出的问题。

To create an (isolated) clone of a given System.Data.DataRowinstance, you can do the following:

要创建给定System.Data.DataRow实例的(隔离)克隆,您可以执行以下操作:

// Assume that variable `table` contains the source data table.

// Create an auxiliary, empty, column-structure-only clone of the source data table.
var tableAux = table.Clone();
// Note: .Copy(), by contrast, would clone the data rows also.

// Select the data row to clone, e.g. the 2nd one:
var row = table.Rows[1];

// Import the data row of interest into the aux. table.
// This creates a *shallow clone* of it.
// Note: If you'll be *reusing* the aux. table for single-row cloning later, call
//       tableAux.Clear() first.
tableAux.ImportRow(row);

// Extract the cloned row from the aux. table:
var rowClone = tableAux.Rows[0];

Note: Shallowcloning is performed, which works as-is with column values that are value typeinstances, but more work would be needed to also create independent copies of column values containing reference typeinstances (and creating such independent copies isn't always possible).

注意:执行克隆,它对作为值类型实例的列值按原样工作,但还需要更多的工作来创建包含引用类型实例的列值的独立副本(并且创建这样的独立副本并不总是可能的) )。

回答by Bolle

It seems you don't want to keep the whole DataTable as a copy, because you only need some rows, right? If you got a creteria you can specify with a select on the table, you could copy just those rows to an extra backup array of DataRow like

您似乎不想将整个 DataTable 保留为副本,因为您只需要一些行,对吗?如果您有一个 creteria,您可以使用表上的选择指定,您可以将这些行复制到 DataRow 的额外备份数组中,例如

DataRow[] rows = sourceTable.Select("searchColumn = value");

The .Select() function got several options and this one e.g. can be read as a SQL

.Select() 函数有几个选项,例如这个可以作为 SQL 读取

SELECT * FROM sourceTable WHERE searchColumn = value;

Then you can import the rows you want as described above.

然后您可以如上所述导入所需的行。

targetTable.ImportRows(rows[n])

...for any valid n you like, but the columns need to be the same in each table.

...对于您喜欢的任何有效 n,但每个表中的列必须相同。

Some things you should know about ImportRow is that there will be errors during runtime when using primary keys!

关于ImportRow你应该知道的一些事情是在运行时使用主键时会出现错误!

First I wanted to check whether a row already existed which also failed due to a missing primary key, but then the check always failed. In the end I decided to clear the existing rows completely and import the rows I wanted again.

首先,我想检查是否已经存在由于缺少主键而失败的行,但是检查总是失败。最后我决定完全清除现有行并再次导入我想要的行。

The second issue did help to understand what happens. The way I'm using the import function is to duplicate rows with an exchanged entry in one column. I realized that it always changed and it still was a reference to the row in the array. I first had to import the original and then change the entry I wanted.

第二个问题确实有助于理解会发生什么。我使用导入函数的方式是复制一列中带有交换条目的行。我意识到它总是改变,它仍然是对数组中行的引用。我首先必须导入原件,然后更改我想要的条目。

The reference also explains the primary key errors that appeared when I first tried to import the row as it really was doubled up.

该参考还解释了当我第一次尝试导入该行时出现的主键错误,因为它确实被加倍了。