本文介绍了如何动态创建 Expression<Func<MyClass, bool>>谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何使用表达式树来动态创建一个看起来像......的谓词

How would I go about using an Expression Tree to dynamically create a predicate that looks something like...

(p.Length== 5) && (p.SomeOtherProperty == "hello") 

这样我就可以将谓词粘贴到像这样的 lambda 表达式中...

So that I can stick the predicate into a lambda expression like so...

q.Where(myDynamicExpression)...

我只需要指向正确的方向.

I just need to be pointed in the right direction.

更新: 抱歉各位,我忽略了我希望谓词具有上述多个条件的事实.抱歉造成混乱.

Update: Sorry folks, I left out the fact that I want the predicate to have multiple conditions as above. Sorry for the confusion.

推荐答案

原创

像这样:

    var param = Expression.Parameter(typeof(string), "p");
    var len = Expression.PropertyOrField(param, "Length");
    var body = Expression.Equal(
        len, Expression.Constant(5));

    var lambda = Expression.Lambda<Func<string, bool>>(
        body, param);

更新

re (p.Length== 5) &&(p.SomeOtherProperty == "hello"):

var param = Expression.Parameter(typeof(SomeType), "p");
var body = Expression.AndAlso(
       Expression.Equal(
            Expression.PropertyOrField(param, "Length"),
            Expression.Constant(5)
       ),
       Expression.Equal(
            Expression.PropertyOrField(param, "SomeOtherProperty"),
            Expression.Constant("hello")
       ));
var lambda = Expression.Lambda<Func<SomeType, bool>>(body, param);

这篇关于如何动态创建 Expression<Func<MyClass, bool>>谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 16:05