How to compare two Viewmodel

Asked

Viewed 51 times

0

I have the following doubt, imagine there are two ViewModel:

public CustoViewModel cvm = new CustoViewModel();
public CustoViewModel custoViewModel= new CustoViewModel();

And that each ViewModel have your values separated

cvm.cod = 10;
cvm.desc = "Teste";

custoViewModel.cod = 11;
custoViewModel.desc = "Teste";

I’m doing the comparison below and I know it returns me false

if(!cvm.Equals(custoViewModel))
{
     //Comentario
}

What I want to know is this: if it’s different, I need to take the field that’s different the way it is:

cvm.cod = custoViewModel.cod;

This in this example becomes easy because I put only two fields, but when there are more fields, then to finish: Is there any way to get the different fields without having to do several if ? (Any way that is different from the one shown below)

if(!cvm.Equals(custoViewModel))
{
     if(cvm.cod == custoViewModel.cod)
     {
          cvm.cod = custoViewModel.cod;
     }
     if(cvm.desc== custoViewModel.desc)
     {
          cvm.desc= custoViewModel.desc;
     }
}
  • you do this using Reflection

  • I’ll do a search and see how it works @Ricardopunctual

  • 'Cause you need to do it for a reason?

1 answer

0


You can override the Equals method of the Custoviewmodel class

    public override bool Equals (object o)  
    {
        if (this.Id == o.Id && this.Nome == o.Nome)
        {
            return true;
        }
        else
        {
            return false;
        }
}

the return of the above method, would be true if the attributes of the instances are equal, if you want to compare only the id you can remove && this.Nome == o.Nome, ai then will only copy the entity id

more information http://gabsferreira.com/a-maneira-certa-de-comparar-objetos-em-c/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.