0

I have two data tables, Datatable1 and Datatable2. Datatable1 is subset of the other. I want to find out which rows are new, which of them are matching and which of them non-matching. Want to add a new row in Datatable1 with values - new, matching, and non-matching. Please suggest an optimized way to do this.

For Example: Datatable1:

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name1", typeof(string));
table.Columns.Add("Name2", typeof(string));
//New
table.Rows.Add(25, "Ciya", "David");
table.Rows.Add(51, "Kiya", "Cecil");
//Matching 
table.Rows.Add(50, "Bina", "Cecil");
//Non matching
table.Rows.Add(21, "Riya", "Janet");
table.Rows.Add(10, "Rita", "Christoff");

Datatable2:

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name1", typeof(string));
table.Columns.Add("Name2", typeof(string));

table.Rows.Add(10, "Lisa", "Christoff");
table.Rows.Add(21, "Combivent", "Janet");
table.Rows.Add(50, "Bina", "Cecil");
Learner
  • 93
  • 2
  • 11
  • 1
    Have a look at the ["Related"](http://stackoverflow.com/questions/164144/compare-two-datatables-to-determine-rows-in-one-but-not-the-other) list of questions on the right of this page. You'll find may different answers that provide you opportunities to try (and learn at the same time). Once you've tried, and have a more specific issue, then come back and ask about that if you can't find any answers yourself. – Mr Moose Mar 19 '15 at 06:35

1 Answers1

1

You can try with the Linq methods which are available for Enumerable types like Intersect, Except. Here is an example of doing this.

// Get matching rows from the two tables
IEnumerable<DataRow> matchingRows = table1.AsEnumerable().Intersect(table2.AsEnumerable());

// Get rows those are present in table2 but not in table1
IEnumerable<DataRow> rowsNotInTableA = table2.AsEnumerable().Except(table1.AsEnumerable()); 
Sachin
  • 40,216
  • 7
  • 90
  • 102