Merge 2 DataTables and store in a new one

Xaisoft picture Xaisoft · Nov 12, 2008 · Viewed 151.6k times · Source

If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do:

 dtOne.Merge(dtTwo);

Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?

I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:

//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);

Answer

Jeromy Irvine picture Jeromy Irvine · Nov 12, 2008

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);