Compare properties of an object with properties of a list

1

I have a method:

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


}

Where I get a DTO list and need to check if some properties are the same on 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 to the object list so that it matches what I want. Is there a more general way of doing this? Or a better way?

    
asked by anonymous 12.07.2016 / 15:24

2 answers

2

Yes. One I've just replied on the gringo exactly about it . Below I will post an extension method to bring the different properties between two objects. Just adapt it 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 look something like this:

var valoresModificados = requisicao.ValoresDiferentes<RequisicaoFisicaDTO>(requisicaoDaSuaLista).ToList();
    
12.07.2016 / 15:33
2

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

You have to think if you make up for this, you have to use a lot.

It is slower and less reliable. Maybe you need to adapt something, maybe reverse the list to ignore if the list to ignore most of the time is too big.

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

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;
}
    
12.07.2016 / 15:33