Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to check if all properties, except for two, matches between two objects? [duplicate]

Tags:

c#

.net-core

I have a database containing components with about 20 properties. To find out if an update is needed I want to check if all properties for the two objects, except DateCreated and Id, matches. If all matches no update, if not, update db.

Component comp_InApp = new Component()
{
    Id = null,
    Description = "Commponent",
    Price = 100,
    DateCreated = "2019-01-30",
    // Twenty more prop
};

Component comp_InDb = new Component()
{
    Id = 1,
    Description = "Component",
    Price = 100,
    DateCreated = "2019-01-01",
    // Twenty more prop
};

// Check if all properties match, except DateCreated and Id.
if (comp_InApp.Description == comp_InDb.Description &&
    comp_InApp.Price == comp_InDb.Price
    // Twenty more prop
    )
{
    // Everything up to date.
}
else
{
    // Update db.
}

This works, but it's not a very clean way with 20 properties. Is there a better way of achieiving the same result in a cleaner way?

like image 495
Petter Vennberg Avatar asked Jan 30 '19 11:01

Petter Vennberg


1 Answers

I am using DeepEqual when I don't want/don't have the time to write myself Equals and GetHashCode methods.

You can install it simply from NuGet with:

Install-Package DeepEqual

and use it like:

    if (comp_InApp.IsDeepEqual(comp_InDb))
    {
        // Everything up to date.
    }
    else
    {
        // Update db.
    }

But keep in mind that this will only work for your case when you want to explicitly compare objects, but not for the case when you want to remove an object form a List or cases like this, when Equals and GetHashCode are invoked.

like image 141
meJustAndrew Avatar answered Sep 29 '22 20:09

meJustAndrew