Jump to content
Xtreme .Net Talk

What is the Most Efficient Way to copy a table in a dataset to another dataset


Recommended Posts

Posted

The Copy method in the DataTable class will copy the table structure and its data. This will work fine for you provided that you are not storing reference types in your table. If you are then you must remember that the value of the reference type is the reference. This means that both tables will hold a reference to the same object after the copy operation has completed.

 

Lets say you have this class:

class MyClass
{
   public int a;

   public MyClass(int a)
   {
       this.a = a;
   }
}

And use it like:

static void Main(string[] args)
{
   DataTable dtA = new DataTable();
   dtA.Columns.Add(new DataColumn("Col A", typeof(MyClass)));

   dtA.Rows.Add(new MyClass(100));

   DataTable dtB = dtA.Copy();

   // both tables hold a reference to the same object...
   ((MyClass)dtA.Rows[0][0]).a = 3000;
              
   // "3000" is displayed here for both
   Console.WriteLine(((MyClass)dtA.Rows[0][0]).a);
   Console.WriteLine(((MyClass)dtB.Rows[0][0]).a);

   Console.WriteLine("Done...");
   Console.ReadLine();
}

If you're using value types in your data table, then you do not need to worry about this.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...