Pau*_*ews 105 c# datatable datarow
我正在寻找一种简单的方法来克隆DataRow.有点像拍摄该行的快照并保存它.然后原始Row的值可以自由更改,但我们仍然有另一个保存的副本不会更改.这是正确的方法吗?
DataRow Source, Destination;
//Assume we create some columns and fill them with values
Destination.ItemArray = Source.ItemArray;
Run Code Online (Sandbox Code Playgroud)
这只是将Snapshot的ItemArray引用设置为指向Source中的那个或者它实际上是否单独创建一个副本?我应该这样做吗?
Destination.ItemArray = Source.ItemArray.Clone();
Run Code Online (Sandbox Code Playgroud)
编辑:我不认为第二个代码片段实际编译.
cuo*_*gle 174
您可以使用ImportRow方法将Row从DataTable复制到具有相同模式的DataTable:
var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);
Run Code Online (Sandbox Code Playgroud)
更新:
使用您的新编辑,我相信:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
Run Code Online (Sandbox Code Playgroud)
将工作
注意:cuongle 的 helfpul 答案包含了所有要素,但解决方案可以简化(不需要.ItemArray),并且可以重新构建以更好地匹配所提出的问题。
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];
Run Code Online (Sandbox Code Playgroud)
注意:执行浅克隆,它按原样处理作为值类型实例的列值,但还需要更多工作来创建包含引用类型实例的列值的独立副本(并且创建此类独立副本并不总是可能的) )。