Merging DataTables by Primary Key

We often come across the need to merge DataTable.

In this blog, we are going to learn how to provide Primary Key to the DataTables and then merge them on the same basis.

DataTables with the following structure:
 
DataTable1:  
 
 Source  Target  Name
 4  1  Article
 15  2  Blog
 30   3  Code Snippet
 
DataTable2:

 Target  Description
 1  This is an article
 2  This is a blog
 3  This is a code snippet
 
We want the following output:
 
Final DataTable: 

 Target  Source  Name  Description
 1  4  Article  This is an article
 2  15  Blog  This is a blog
 3  30  Code Snippet  This is a code snippet
 
In order to do that, we provide Primary Key to the data tables in the following manner:
  1. DataTable1.PrimaryKey = new DataColumn[] { DataTable1.Columns["TARGET"] };                             
  2. DataTable2.PrimaryKey = new DataColumn[] { DataTable2.Columns["TARGET"] };  
  3. DataTable1.Merge(DataTable2);  
Doing that you will get the required output in DataTable1.
Ebook Download
View all
Learn
View all