问题描述
我正在寻找一种简单的方法来克隆DataRow。有点像为该行拍摄快照并将其保存。然后可以自由更改原始Row的值,但我们还有另一个已保存的副本,该副本不变。这是正确的方法吗?
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.
推荐答案
您可以使用可将具有相同模式的行从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);
更新:
使用新的Edit,我相信:
With your new Edit, I believe:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
可以工作
这篇关于复制或克隆DataRow的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!