Cannot compare NAN using expression

I use an expression to compare values, and I use the code below,

Below is a method that creates a lambda expression.

    public static class Test
{
    public static Expression<Func<T, bool>> TransformToPredicate<T>(Expression<Func<T, double>> getvalue, double value)
    {
        System.Linq.Expressions.Expression equals = System.Linq.Expressions.Expression.Equal(getvalue.Body,
                                             System.Linq.Expressions.Expression.Constant(value));
        return System.Linq.Expressions.Expression.Lambda<Func<T, bool>>(equals, getvalue.Parameters);
    }
}

In the code below, when comparing Nan with a Nan value, it returns false. How to overcome this when using Expressioons? Do I need to do this in a more general way?

           Employee emp = new Employee();
        emp.SickLeaveHours = double.NaN;
        Expression<Func<Employee, double>> getfunc = x => x.SickLeaveHours;
        var predicate = Test.TransformToPredicate<Employee>(getfunc, double.NaN);
        var func = predicate.Compile();
        var flag = func(emp);

The below code works fine when I use a value other than Nan.

            Employee emp = new Employee();
        emp.SickLeaveHours = 10.0;
        Expression<Func<Employee, double>> getfunc = x => x.SickLeaveHours;
        var predicate = Test.TransformToPredicate<Employee>(getfunc, 10.0);
        var func = predicate.Compile();
        var flag = func(emp);

I know double.Nan == double.Nan will return false, and we must use either double.IsNAN or the value! = Value. But I'm not sure how to do this using expressions.

+3
source share
1 answer

. . Equals(). , Equals. equals Expression.Equal.

:

var wrong =
    System.Linq.Expressions.Expression.Lambda<Func<bool>>(
    System.Linq.Expressions.Expression.Equal(System.Linq.Expressions.Expression.Constant(double.NaN),
    System.Linq.Expressions.Expression.Constant(double.NaN))).Compile();

// is always false
bool result = wrong();

ConstantExpression first = System.Linq.Expressions.Expression.Constant(double.NaN, typeof(double));
ConstantExpression second = System.Linq.Expressions.Expression.Constant(double.NaN, typeof(double));

var right =
    System.Linq.Expressions.Expression.Lambda<Func<bool>>(
    System.Linq.Expressions.Expression.Call(first, first.Type.GetMethod("Equals", new[] { second.Type }), second)).Compile();

// will always be true
result = right();
+3

All Articles