Search code examples
c#.netdatatable

Subtract two DataTables that have the same schema, e.g Minus SQL query


I have two DataTables that have both the same schema (same columns names and types) .I want to get the rows that appear in the first and not in the second one. Could anyone help me in this? Thanks.


Solution

  • Thankfully, MS has created extension methods for DataTable that let you use Linq methods (like Except) to query data rows, and written a class that implements IEqualityComparer<DataRow> that compares DataRow instances by their column values:

    var rows = dt1.AsEnumerable()
                  .Except(dt2.AsEnumerable(),DataRowComparer.Default);