.NET Compare 2 Datarows by Value Using LINQ

xster
xster
Published in
1 min readJun 21, 2009

There are too many top Google search results giving the impression that it is impossible to compare 2 DataRows for its value contents and the programmer needs to iterate through everything himself.

Such is no longer true in .NET 3.5 but the blogosphere doesn’t seem to have caught on yet.

It is possible, given 2 DataTables or any other enumerable object types, to compare its contents using LINQ in just one line of code.

I will give an example in VB where I’d want to compare all column properties (description, data type, field length, etc) of all tables in 2 supposedly identical SQL databases.

  1. Read into DataTable the SQL command
SELECT * FROM information_schema.columns
WHERE TABLE_SCHEMA = 'dbo'
ORDER BY TABLE_NAME, COLUMN_NAME
  1. To get the difference, you can use the Except LINQ operator on the 2 tables and use a DataRowComparer class to check for value equality instead of reference equality
Dim differenceTable = masterTable.AsEnumerable.Except(subjectTable.AsEnumerable, DataRowComparer.Default)

This solution is ideal when there is no key column. Otherwise, merge the second table into the first and call .GetDifference() for a easier way to find the different rows.

Reference: http://msdn.microsoft.com/en-us/library/bb386998.aspx

--

--