user2431727
user2431727

Reputation: 907

Combine two datatable with common column c#

I have two table as below Table1

   IntervalID(pK)
       1
       2
       3

Table 2

IntervalID  Name
1           XXX

Output should be (Table1+Table2)

IntervalID  Name
1           XXX
2          NULL
3          NULL

I have done like below

Table1.Merge(Table2);

But it does not give desired output

Upvotes: 1

Views: 616

Answers (1)

Mohammed Sajid
Mohammed Sajid

Reputation: 4913

You could achieve this by using Left join, like the following code:

var result = (from t1 in table1
              join t2 in table2 on t1.IntervalId equals t2.IntervalId into leftedResults
              from leftedResult in leftedResults.DefaultIfEmpty()
              select new { t1.IntervalId, Name = leftedResult?.Name }).ToList();

Note that, you can't merge two DataTables that not have similar schemas.

Left join for DataTables :

var result = (from t1 in dataTable1.AsEnumerable()
          join t2 in dataTable2.AsEnumerable() on t1.Field<int>("IntervalId") equals t2.Field<int>("IntervalId") into leftedResults
          from leftedReult in leftedResults.DefaultIfEmpty()
          select new { IntervalId = t1.Field<int>("IntervalId"), Name = leftedReult?.Field<string>("Name") }).ToList();

I hope you find this helpful.

Upvotes: 2

Related Questions