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.
source
share