简体   繁体   中英

More Efficient way to Copy DataRows into another DataTable

This question is about finding a more efficient way for a simple problem. I have two DataTables with same structure (ie the Columns have same name with same Ordinals). Let them Call DataTable A and DataTable B . Assume both have 100 rows. Now I want to copy all the rows of DataTable B to DataTable A without removing rows from DataTable A . So in the end DataTable A has 200 rows. I did it as shown below.

for (int i = 0; i < B.Rows.Count - 1;i++ )
    {
        DataRow dr = B.Rows[i];
        A.Rows.Add(dr);
    }

The issue is I do not want to loop. Is there a direct way to copy it, without looping. The whole 100 rows at once. Is there a function which specifies the set of rows you want to copy.

There are some problems with your simple approach because it doesnt handle primary key violations. Try BeginLoadData, LoadDataRow and EndLoadData. This should be more efficient. BeginLoadData and EndLoadData call only once.

As far as I know, there is no other way of copying multiple rows from one Datatable to another than iterating through all the rows. In fact, on MSDN there is an article telling you how to copy rows between Datatables and uses an iteration loop.

https://support.microsoft.com/en-gb/kb/305346

If you just need a new independent DataTable instance to work with and do not need to append rows to an existing DataTable, then the DataView.ToTable() method is very convenient.

https://msdn.microsoft.com/en-us/library/a8ycds2f(v=vs.110).aspx

It creates a separate copy with the same schema and content.

DataTable objTableB = objTableA.DefaultView.ToTable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM