Question

This method compares two objects of the same class:

foreach (var field in fields.Where(field => !objTarget
        .GetType().GetProperty(field).GetValue(objTarget, null)
        .Equals(obj.GetType().GetProperty(field).GetValue(obj, null))))

If the both property have values it works normaly, but sometimes i have a null property in one of these 2 objects, how can i deal with it?

EDIT: If im comparing two objects, i.e:

var a = new Test();
var b = new Test();
a.Property1 = "1";
b.Property1 = null;

im getting the null reference exception:

An unhandled exception of type 'System.NullReferenceException' occurred in ConsoleApplication1.exe

Était-ce utile?

La solution

Instead of using LINQ and Where method get the values to variables and put your condition inside loop:

foreach (var field in fields)
{
    var val1 = objTarget.GetType().GetProperty(field).GetValue(objTarget, null);
    var val2 = obj.GetType().GetProperty(field).GetValue(obj, null));

    if(val1 == null and val2 != null || val1 != null && !val1.Equals(val2))
    {
        // your code
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top