How Build Lambda Expression Tree with multiple con

2019-02-02 09:38发布

问题:

Note: I know it's much simple to create this using dynamic linq but I want to learn.

I want to create a lambda that "finds": Name=David AND Age=10.

 class Person
    {
       public int Age { get; set; }
       public string Name { get; set; }
    }

    var lambda = LabmdaExpression<Person>("Name", "David", "Age", 10);

static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1, string property2, int value2)
{

     ParameterExpression parameterExpression = Expression.Parameter(typeof(Person), "o");
     MemberExpression memberExpression1 = Expression.PropertyOrField(parameterExpression, property1);
     MemberExpression memberExpression2 = Expression.PropertyOrField(parameterExpression, property2);

     ConstantExpression valueExpression1 = Expression.Constant(value1, typeof(string));
     ConstantExpression valueExpression2 = Expression.Constant(value2, typeof(int));

     BinaryExpression binaryExpression1 = Expression.Equal(memberExpression1, valueExpression1);
     BinaryExpression binaryExpression2 = Expression.Equal(memberExpression2, valueExpression2);

     var ret1 =   Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
     var ret2 =   Expression.Lambda<Func<T, bool>>(binaryExpression2, parameterExpression);


   }

回答1:

Expression andExpression = Expression.AndAlso(binaryExpression1, binaryExpression2);

return Expression.Lambda<Func<T, bool>>(andExpression , parameterExpression);

Edit - comment

You just chain together all your expresions

so in order to get this expression X AND (Y OR (Z OR Q))

Expression ZorQ = Expression.OrElse(zExp, qExp);
Expression YorZorQ = Expression.OrElse(yExp, ZorQ);
Expression XandYorZorQ = Expression.AndAlso(xExp, YorZorQ);