Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Two Datasets - Find Changes - LINQ

Tags:

c#

linq

I've scoured the internet to try and find a solution for this, and perhaps I'm not going about this the right way.

I need to compare two datasets, identical in structure, and would like to find new and changed objects (using LINQ).

Using what I've found at CodeProject, I was able to pull together a list of items that have changed, but this was done by hard-coding each column (and there will be many) and checking for identical values:

var updRec = from u in updated
             join o in orig
                on u.KeyValue equals o.KeyValue
             where
                (o.Propery1 != u.Propery1) ||
                (o.Propery2 != u.Propery2)
             select new record
             {
                 KeyValue = u.KeyValue,
                 Propery1 = u.Propery1,
                 Propery2 = u.Propery2 ,
                 RecordType = "mod" // Modified
             };

I could use help with 2 things:

  1. Is there a more efficient way to loop through each of the columns, as I plan on adding many more properties that I need to compare? There has to be a better way to dynamically check 2 identical datasets for changes.
  2. How can I see which propery has changed? For example, creating a list of 'Property, OriginalValue, UpdatedValue' for all items that are not identical?

Hopefully that explains it well. Please feel free to point me at other ways of handling this scenario if I'm not looking at it correctly.

like image 476
JBickford Avatar asked Aug 29 '13 18:08

JBickford


1 Answers

You can use the LINQ Except() extension method. That returns everything in a list except what is in the second list.

var orignalContacts = GetOrignal();
var updatedContacts = GetUpdated();

var changedAndNew = updatedContacts.Except(orignalContacts);
var unchanged     = orignalContacts.Except(updatedContacts);

Depending on your data provider you may need to overide Equals() and GetHashCode() on your objects.

like image 113
DarcyThomas Avatar answered Oct 16 '22 07:10

DarcyThomas