Compare properties of an object with properties of a list

Asked

Viewed 1,274 times

1

I have a method:

public void MetodoAleatorio(List<RequisicaoFisicaDTO> lstRequisicaoFisicaDtos)
{
    RequisicaoFisicaDTO requisicao = lstRequisicaoFisicaDtos.FirstOrDefault();


}

Where I get a list of DTO and need to check if some properties are equal in all received objects, for example:

lstRequisicoes.All(x => x.IdTipoObjeto == requisicao.IdTipoObjeto);

I have about 12 properties of this object that need to be compared with the list of objects to fit what I want. Is there a more generic way to do this? Or a better way?

2 answers

3

In that answer in the OS I found something that is more or less what you want.

You have to think if it pays to use this, you have to use it a lot.

It’s slower and less reliable. Maybe you need to adapt something, who knows how to reverse the situation of the list to ignore if most of the time the list to ignore is too big.

It has other implications, if changing the object structure can change the behavior of this method and give different results than expected.

public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class {
    if (self != null && to != null) {
        var type = typeof(T);
        var ignoreList = new List<string>(ignore);
        var unequalProperties =
            from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
            where !ignoreList.Contains(pi.Name)
            let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
            let toValue = type.GetProperty(pi.Name).GetValue(to, null)
            where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
            select selfValue;
        return !unequalProperties.Any();
    }
    return self == to;
}

I put in the Github for future reference.

2


Yes. Once I answered in the SO gringo exactly about this. Below I will post an extension method to bring the different properties between two objects. Just you adapt to your logic:

namespace SeuProjeto.Extensions
{
    public static class ModelExtensions
    {
        public static IEnumerable<KeyValuePair<string, object>> ValoresDiferentes<T>(this T obj, T modifiedObject) 
        {
            foreach (var property in typeof(T).GetProperties().Where(p => !p.GetGetMethod().IsVirtual))
            {
                if (property.GetValue(obj).ToString() != property.GetValue(modifiedObject).ToString())
                {
                    yield return new KeyValuePair<string, object>(property.Name, property.GetValue(modifiedObject));
                }
            }
        }
    }
}

It would be something like that:

var valoresModificados = requisicao.ValoresDiferentes<RequisicaoFisicaDTO>(requisicaoDaSuaLista).ToList();

Browser other questions tagged

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