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

gprabaka

Newcomer
Joined
Jul 14, 2005
Messages
21
Good Afternoon,
What is the most efficient way, in your opinion, to copy the the data structure and data from a table in a dataset to another dataset?
Thanks
Guha
 
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:
C#:
class MyClass
{
    public int a;

    public MyClass(int a)
    {
        this.a = a;
    }
}
And use it like:
C#:
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.
 
Back
Top