Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a bool? is True in Dynamic Lambda

Tags:

c#

lambda

linq

I'm doing a search form that has a few different options and have it all working except this one part.

For reference I'm posting the entire method but the issue I'm having is trying to do a dynamic expression to check a bool? property.

This line of code is where I'm having the problem...

call = Expression.IsTrue(propertyAccess); //TODO: Check if the property is true

As written it complains about bool to bool? conversion. If I change it to a bool instead of bool? it complains that IsTrue is not a valid Linq expression.

Basically I want to do x => x.UltrasonicTest == true but don't know how to set that to a MethodCallExpression.

Here is the short version of the code...

public ActionResult Search(List<string> selectedTests)
    {
        IQueryable<Logbook> logbooks;
        Expression lambdaStatus = null;
        Expression lambdaTests = null;
        Expression lambdaFinal = null;

        ParameterExpression parameter = Expression.Parameter(typeof(Logbook), "logbook");
        Expression call = null;
        PropertyInfo property = null;

        property = typeof(Logbook).GetProperty("UltrasonicTest");

        if (property != null)
        {
            MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property);
            call = Expression.IsTrue(propertyAccess); //TODO: Check if the property is true

            lambdaTests = call;
        }

        lambdaFinal = Expression.And(lambdaStatus, lambdaTests);

        Expression<Func<Logbook, bool>> predicate = Expression.Lambda<Func<Logbook, bool>>(lambdaFinal, parameter);
        logbooks = db.Logbooks.Where(predicate);

        List<Logbook> filteredLogbooks = logbooks.OrderByDescending(x => x.DateEntered.Value).Take(50).ToList();

        return View("Index", filteredLogbooks);
    }
like image 614
Bradley Gatewood Avatar asked Apr 20 '26 13:04

Bradley Gatewood


1 Answers

Rather than attempting to create a MethodCallExpression try constructing a BinaryExpression with the right as a Constant of true.

Something like this:

call = Expression.MakeBinary(ExpressionType.Equal, propertyAccess, Expression.Constant(true, typeof(bool?)));

Edit

Or tidier option:

call = Expression.Equal(propertyAccess, Expression.Constant(true, typeof(bool?)));
like image 156
Brent Mannering Avatar answered Apr 22 '26 03:04

Brent Mannering