fork download
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. var boolExpression = ConvertToBool<Model>(m => m.NullableBoolHere);
  9.  
  10. // Test:
  11. Console.WriteLine(boolExpression.Compile()(new Model(){NullableBoolHere = true } ));
  12. Console.WriteLine(boolExpression.Compile()(new Model(){NullableBoolHere = false } ));
  13. Console.WriteLine(boolExpression.Compile()(new Model(){NullableBoolHere = null } ));
  14. }
  15.  
  16. public static Expression<Func<TModel, bool>> ConvertToBool<TModel>(Expression<Func<TModel, bool?>> expression)
  17. {
  18. var body = Expression.Coalesce(expression.Body, Expression.Constant(false));
  19. var boolExpression = (Expression<Func<TModel, bool>>)
  20. Expression.Lambda(body, expression.Parameters.First());
  21. return boolExpression;
  22. }
  23.  
  24. class Model
  25. {
  26. public bool? NullableBoolHere {get;set;}
  27. }
  28. }
Success #stdin #stdout 0.08s 34360KB
stdin
stdout
True
False
False