问题描述
我正在寻找一种简单的方法来克隆 DataRow.有点像拍摄该行的快照并保存它.然后原始行的值可以自由更改,但我们仍然有另一个不会更改的已保存副本.这是正确的做法吗?
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 Source, Destination;
// Assume we create some columns and fill them with values
Destination.ItemArray = Source.ItemArray;
这只是将 Snapshot 的 ItemArray 引用设置为指向 Source 中的引用还是它实际上制作了一个单独的副本?我应该这样做吗?
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?
Destination.ItemArray = Source.ItemArray.Clone();
我认为第二个代码片段实际上没有编译.
I don't think the second code snippet actually compiles.
推荐答案
您可以使用 ImportRow
方法 将 Row 从 DataTable 复制到具有相同架构的 DataTable:
You can use ImportRow
method to copy Row from DataTable to DataTable with the same schema:
var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);
更新:
有了你的新编辑,我相信:
With your new Edit, I believe:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
会起作用
这篇关于复制或克隆 DataRow 的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!