-1

I have 2 data models with same properties which I gets data from 2 web API responses. I am trying to compare 2 models with values, If data difference is found, I need to compare ,find differences if found assign to a new instance of data model or existing one which is latest.

Ex: UserProfile1 contains latest data.

What is best approach to compare 2 data models (not a list) ? Currently I am using if-else approach where as I have 25 properties for a single data model.

Is it possible with Icomparer ?

UserProfile userProfile1 = new UserProfile()
{
    Name = "Satya",
    AddressLine1 = "RailwayRoad",
    AddressLine2 = "MG Street",
    AddressLine3 = "India"
    };

UserProfile userProfile2 = new UserProfile()
{
    Name = "Satya",
    AddressLine1 = "RailwayRoad",
    AddressLine2 = "Metro Street",
    AddressLine3 = "India"
};

if(userProfile1.Equals(userProfile2))
{
    // I tried like this 
}

bool isUserDetailsDiff = false;
if (!string.Equals(userProfile1.Name, userProfile2.Name))
{
    isUserDetailsDiff = true;
    userProfile1.Name = userProfile2.Name;
}
else if (!string.Equals(userProfile1.AddressLine1, userProfile2.AddressLine2))
{
    isUserDetailsDiff = true;
    userProfile1.AddressLine1 = userProfile2.AddressLine2;
}
dodekja
  • 537
  • 11
  • 24
PavanKumar GVVS
  • 859
  • 14
  • 45
  • `Data Model` is an abstract term, neither a container nor an object that can be compared with something else. You're asking how to perform a deep comparison of two *objects*, `userProfile2` and `userProfile1`. There are several SO question about this. [like this one](https://stackoverflow.com/questions/375996/compare-the-content-of-two-objects-for-equality). There's no easy solution though. Either you use reflection to compare properties, or `IEquatable` and recursion for complex properties – Panagiotis Kanavos Oct 24 '22 at 12:47
  • This question is answered here: https://stackoverflow.com/a/10454552/8336973 – RedFox Oct 24 '22 at 12:48
  • Why do you refer to the objects as `data model`s? Are you trying to save differences to the database? Or make EF behave a certain way? Send changes to a client? – Panagiotis Kanavos Oct 24 '22 at 12:48
  • There is also `record` - syntax sugar which would generate `IEquatable` code – Selvin Oct 24 '22 at 13:03

1 Answers1

1

You can declare UserProfile as record and you can compare them by doing this userProfile1 == userProfile2

public record UserProfile(
string Name,
string AddressLine1,
string AddressLine2,
string AddressLine3
);

public class Example
{
    public void ExampleMethod()
    {
        var userProfile1 = new UserProfile("Satya", "RailwayRoad", "MG Street", "India");
        var userProfile2 = new UserProfile("Satya", "RailwayRoad", "MG Street", "India");

        if (userProfile1 == userProfile2)
        {
           //...
        }
    }
}
Aurel
  • 98
  • 1
  • 11