how to compare values of two reference type nested and dynamic objects

599 views Asked by At

I have two objects with the same type and values how can I compare them by value?

exp:

    class Person 
    {
    
    public string Name { get; set; }
    
    public DateTime BirthDate { get; set; }

    public Address Address { get; set; }
    
    }

class Address
    {
    
    public string City { get; set; }
    
    public int ZipCode { get; set; }
    
    }
    
    var p1 = new Person()
    {
    Name = "John doe",
    BirthDate = new DateTime(2000, 1, 1),
    Address = new Address(){
         City = "some city",
         ZipCode = 123456
    }
    };
    
    var p2 = new Person()
    {
    Name = "John doe",
    BirthDate = new DateTime(2000, 1, 1),
    Address = new Address(){
        City = "some city",
        ZipCode = 123456
    }
    };

so how can I compare these objects with value?

Mabey in future I wanna change my objects so I need a general way that not depends on object properties names and types

2

There are 2 answers

1
goldenbull On BEST ANSWER

use json

Convert each object into a json string, with all properties/fields sorted by name, then compare two strings. this is slow, but it works.

use reflection

Using reflection methods, compare each property/field one by one. Actually the json library do the same job. Doing the comparison yourself will save the time converting to string, but you have to dive into the nested types.

use some code generator, e.g. protobuf

If the datatype is just POCO type, maybe protobuf is a good choice. It introduces a lot advantages:

  • build-in comparison
  • json serialization and deserialization
  • very fast binary serialization and deserialization
  • cross-platform and cross language, integrated well with grpc inter-process communication
  • version compatibility, when new fields added, old data on disk can still be read by app.
0
Siegfried.V On

just make an "Equal function" in your Person class

public bool class Equals(Person source)
{
    if(this.Name!=source.Name) return false;
    if(this.Surname!=source.Surname)return false;
    ....
    return true;
}

Then use like that :

if(myFirstPerson.Equals(mySecondPerson))
{
    
}

Like that you can place as many as attributes as you want, then even make several Equals functions, if you need not to always compare the same attributes. Personally I always use this way (instead of "if values equal", I put "if value not equal then return false"), cause very useful when you have a lot of values to compare, and different equal functions.