【问题标题】:How to move DataTable to another DataSet?如何将 DataTable 移动到另一个 DataSet?
【发布时间】:2018-08-20 07:06:16
【问题描述】:

如何将 DataTable 对象从一个数据集移动到另一个数据集并避免在内存中重复数据?像这样的东西:

var ds1 = new DataSet();
var ds2 = new DataSet();
IDataAdapter da = myDataAdapterFactory.New();
da.Fill(ds1);
Console.WriteLine(ds1.Tables.Count);//1 
Console.WriteLine(ds2.Tables.Count);//0 
ds1.MoveDataTableTo(ds2, ds1.Tables[0]);
Console.WriteLine(ds1.Tables.Count);//0 
Console.WriteLine(ds2.Tables.Count);//1 

我无法消耗内存,这也是我不使用DataTable.Copy()DataSet.Merge()或其他方式复制内存行的原因。

【问题讨论】:

  • 你尝试了什么? documentation saysAddRemoveCopyToDataTableCollection的方法中。
  • @jeroenh 我不需要 copy ,我需要 move
  • true,对副本的接受答案也没有解决问题的“避免在内存中复制数据”部分。
  • 你试过dt = ds1.Tables[0]; ds1.Remove(dt); ds2.Add(dt);吗?
  • @jeroenh,它奏效了。请问可以发一下答案吗?目前,我看到它很简单,但我花了很多时间寻找解决方案。

标签: c# datatable


【解决方案1】:

你可以把你需要移动的数据表,Remove它从第一个数据集和Add它移到另一个

var dt = ds1.Tables[0]; 
ds1.Tables.Remove(dt); 
ds2.Tables.Add(dt);

【讨论】:

    【解决方案2】:

    使用此功能

    public DataTable CopyDataTable(DataTable dtSource)
    {
            // cloned to get the structure of source
            DataTable dtDestination = dtSource.Clone();
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dtDestination.ImportRow(dtSource.Rows[i]);
            }
            return dtDestination;
    }
    

    假设您要将 sourceSet 的第一个表复制到 destinationSet。 像这样称呼它

    DataTable destinationTable = CopyDataTable(ds1.Tables[0]);
    DataSet destinationSet = new DataSet();
    ds2.Tables.Add(destinationTable);
    

    【讨论】:

    • 我想避免在内存中重复行。 ImportRow() 将复制它们。
    猜你喜欢
    • 2011-06-21
    • 2022-01-18
    • 2013-12-21
    • 2012-02-08
    • 2012-03-24
    • 2012-11-29
    • 2012-07-24
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多