Click here to Skip to main content
14,698,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys
Any idea on how to merge two datatable like this

table 1

1 | 3 | 5 |

table 2

| 2 | 4 | 6 |

to become

1 | 2 |3 |4 |5 |6

ZurdoDev 5-Feb-15 16:14pm
Just do it in sql, otherwise create a new datatable and add columns manually.
Tomas Takac 6-Feb-15 1:51am
Why do you need t do that? If the data is unrelated (tables have different columns) then what's the benefit?

1 solution

Try this ...

I created tables similar to those you have in your post
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
table1.Columns.Add("1", typeof(string));
table1.Columns.Add("3", typeof(string));
table1.Columns.Add("5", typeof(string));

table2.Columns.Add("2", typeof(string));
table2.Columns.Add("4", typeof(string));
table2.Columns.Add("6", typeof(string));
Then I created a datatable to hold the results
DataTable dtResult = new DataTable();
dtResult.Columns.Add("1", typeof(string));
dtResult.Columns.Add("2", typeof(string));
dtResult.Columns.Add("3", typeof(string));
dtResult.Columns.Add("4", typeof(string));
dtResult.Columns.Add("5", typeof(string));
dtResult.Columns.Add("6", typeof(string));
I then take advantage of the fact that DataTable can be converted to a queryable object
var t1 = table1.AsEnumerable();
var t2 = table2.AsEnumerable();
I had to make the assumption that the "row number" was the way to join the two tables and used this to populate the result
var result = from dataRows1 in t1
             join dataRows2 in t2
             on table1.Rows.IndexOf(dataRows1) equals table2.Rows.IndexOf(dataRows2) into lj
             from r in lj.DefaultIfEmpty()
             select (new object[]

foreach (var x in result)

In summary - I used a Left Join[^] on the tables and selected the columns I needed in the order you required

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900