How to compare datatables to get unmatched datarows using LINQ to Datatable


In this article I am going to explain about how to get unmatched rows from databale in C#. I am using features of Datatable. We can do it in several ways. Using LINQ to datatable is one of the way to do it.

If you want to compare datatable and find unmatched datarows in datatable. For this purpose we will be using LINQ to Datatable For comparing data in datatable both the datatables schema should be same.

Below is your Datatable A
StudID Name City
1 Rohan Pune
2 Sachin Mumbai
3 Vinod Delhi
4 Andy Kanpur
5 Neha Nagpur

Datatable B
StudID Name City
1 Rohan Pune
2 Sachin Hyderabad
3 Andy Delhi
4 Andy Kanpur

Now we will compare Table A and Table B and get unmatched data from A. This should give us rows with StudentID 2,3,5.


IEnumerable dtAEnum = dtA.AsEnumerable();
IEnumerable dtBEnum = dtB.AsEnumerable();
DataTable dtUncommon = dtAEnum.Except(dtAEnum).CopyToDataTable();


Now the datatable dtUncommon has uncommon datarows from datatable A.

Now we will compare Table A and Table B and get unmatched data from Datatable B. This should give us rows with StudentID 2,3.


DataTable dtUncommon = dtBEnum.Except(dtAEnum).CopyToDataTable();

Now the datatable dtUncommon has uncommon datarows from datatable B.


Comments

Guest Author: Balram21 Feb 2013

IEnumerable object have no Except method
so how to call Except function when i use IEnumerable class

Author: Laxmikant01 Apr 2013 Member Level: Gold   Points : 0

Add an appropriate using statement to use LINQ functionality.

using System.Linq



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: