C#简单的方法来复制或克隆一个DataRow? [英] C# simple way to copy or clone a DataRow?

查看:517
本文介绍了C#简单的方法来复制或克隆一个DataRow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个简单的方法,使一个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;

这会不会只是设置快照的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?

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

编辑:我不认为第二code代码实际上编译

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

推荐答案

您可以使用<一个href=\"https://msdn.microsoft.com/en-us/library/system.data.datatable.importrow%28v=vs.110%29.aspx\"><$c$c>ImportRow方法从数据表中复制行的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[];

将工作

这篇关于C#简单的方法来复制或克隆一个DataRow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆