replaysMike / AnyDiff

A CSharp (C#) diff library that allows you to diff two objects and get a list of the differences back.
Other
164 stars 16 forks source link

How to find differences that are nested deep inside a property? #12

Closed SubasishMohapatra closed 4 years ago

SubasishMohapatra commented 4 years ago

How to find differences that are nested deep inside a property? In the classes mentioned below, how do I get the differences which are listed 2 level deep e.g., Cool.Author.Address.City and Cool.Author.Address.Country

 public class Cool
    {
        public int id;
        public int revision;
        public string[] vehicles;
        public Author author;
        public string tagline;
        public Gender gender;
    }

    public class Author
    {
        public string FirstName;
        public string LastName;
        public Address Address;
    }

    public class Address
    {
        public string City;
        public string Country;
    }
replaysMike commented 4 years ago

@SubasishMohapatra what should have been a simple use case turned out to be a bug! I've fixed this in version 1.0.73 - it turned out I had missed a use case in the tests for include/exclude expressions that have a direct path.

Here's an example that should be working now. The following will compare 2 different objects, but only compare City and Country because we specified that the expressions passed are property includes using ComparisonOptions.IncludeList (by default it treats expressions as excludes, same as option ComparisonOptions.ExcludeList)

var obj1 = new Cool {
  Author = new Author {
    FirstName = "John",
    LastName = "Smith",
    Address = new Address { 
      City = "Los Angeles",
      Country = "USA"
    } 
  }
};
var obj1 = new Cool {
  Author = new Author { 
    FirstName = "Jane",
    LastName = "Doe",
    Address = new Address { 
      City = "Beijing",
      Country = "China"
    } 
  }
};

var diff = obj1.Diff(obj2, ComparisonOptions.All | ComparisonOptions.IncludeList, x => x.Author.Address.City, x => x.Author.Address.Country);
Assert.AreEqual(2, diff.Count); // only City and Country are different
replaysMike commented 4 years ago

also note you don't have to use expressions - you could also just pass the path as follows:

var diff = obj1.Diff(obj2, ComparisonOptions.All | ComparisonOptions.IncludeList, ".Author.Address.City", ".Author.Address.Country");