Best way to compare 2 Data models in C# .NET Core

651 Views Asked by At

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;
}
1

There are 1 best solutions below

0
Aurel On

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)
        {
           //...
        }
    }
}