Click here to Skip to main content
15,895,656 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

Is there any way to subtract two datatables in order to have rows of the first datatable that are not in the second one?

I have tried .Except() method like below but it does not work for me.

C#
dt1.AsEnumerable().Except(dt2.AsEnumerable()).CopyToDataTable();
Posted

 
Share this answer
 
Comments
M_Mogharrabi 27-Aug-12 23:16pm    
thanx a lot,it was my solution!!!
pradiprenushe 28-Aug-12 0:17am    
welcome
To get difference in rows use GetChanges method of dataTable.
A Sample below:
C#
public static DataTable CompareTwoDataTable(DataTable dt1, DataTable dt2)
{

dt1.Merge(dt2);

DataTable d3 = dt2.GetChanges();

return d3;
}
 
Share this answer
 
This one is working as expected:

C#
var a = new int[] {1,2,3,4,5};
var b = new int[] {3,4,5,6,7};

var c = a.Except(b);


But both are IEnimerable<int>, in your case, you will get two EnumerableRowCollection<DataRow> collections. I think you will not be able to simply compare them with the defaults. You will need to use the second overload[^], where you can specify your EqualityComparer. Here is a good starting point to implement it: http://www.iramellor.com/LINQ-Distinct-a-DataTable-and-the-IEqualityComparerT[^]
 
Share this answer
 
v2

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