C# 如何动态创建 Expression<Func<MyClass, bool>> 谓词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/845059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:54:28  来源:igfitidea点击:

How do I dynamically create an Expression<Func<MyClass, bool>> predicate?

c#linqlambdaexpression-trees

提问by Senkwe

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

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

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

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

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

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.

更新:抱歉各位,我忽略了我希望谓词具有上述多个条件的事实。对困惑感到抱歉。

采纳答案by Marc Gravell

Original

原来的

Like so:

像这样:

    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);


Updated

更新

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

回复(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);

回答by Daniel Earwicker

To combine several predicates with the &&operator, you join them together two at a time.

要将多个谓词与&&运算符组合在一起,您可以一次将两个谓词连接在一起。

So if you have a list of Expression objects called predicates, do this:

因此,如果您有一个名为 的 Expression 对象列表predicates,请执行以下操作:

Expression combined = predicates.Aggregate((l, r) => Expression.AndAlso(l, r));

回答by Schotime

Use the predicate builder.

使用谓词构建器。

http://www.albahari.com/nutshell/predicatebuilder.aspx

http://www.albahari.com/nutshell/predicatebuilder.aspx

Its pretty easy!

它很容易!

回答by Alan

To associate Lambda expression each other: An other way is to use the following code. It s more flexible than the Schotime answer in my advice and work perfectly. No external Nuggets needed

将 Lambda 表达式相互关联: 另一种方法是使用以下代码。它比我的建议中的 Schotime 答案更灵活并且工作完美。不需要外部掘金队

Framework 4.0

框架 4.0

    // Usage first.Compose(second, Expression.And)
    public static Expression<T> Compose<T>(this Expression<T> First, Expression<T> Second, Func<Expression, Expression, Expression> Merge)
    {
        // build parameter map (from parameters of second to parameters of first)
        Dictionary<ParameterExpression,ParameterExpression> map = First.Parameters.Select((f, i) => new { f, s = Second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

        // replace parameters in the second lambda expression with parameters from the first
        Expression secondBody = ParameterRebinder.ReplaceParameters(map, Second.Body);

        // apply composition of lambda expression bodies to parameters from the first expression 
        return Expression.Lambda<T>(Merge(First.Body, secondBody), First.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> First, Expression<Func<T, bool>> Second)
    {
        return First.Compose(Second, Expression.And);
    }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> First, Expression<Func<T, bool>> second)
    {
        return First.Compose(second, Expression.Or);
    }


public class ParameterRebinder : ExpressionVisitor
{
    private readonly Dictionary<ParameterExpression, ParameterExpression> map;

    public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
    {
        this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
    }

    public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
    {
        return new ParameterRebinder(map).Visit(exp);
    }

    protected override Expression VisitParameter(ParameterExpression p)
    {
        ParameterExpression replacement;
        if (map.TryGetValue(p, out replacement))
        {
            p = replacement;
        }
        return base.VisitParameter(p);
    }
}

回答by MurariAlex

I have a open-source project called Exprelsiorthat provides very simple ways to create dynamic predicates:

我有一个名为Exprelsior的开源项目,它提供了非常简单的方法来创建动态谓词:

Based on your example:

根据您的示例:

var exp1 = ExpressionBuilder.CreateBinary<YourClass>("MyProperty.Length", 5, ExpressionOperator.Equals);

var exp2 = ExpressionBuilder.CreateBinary<YourClass>("SomeOtherProperty", "hello", ExpressionOperator.Equals);

var fullExp = exp1.And(exp2);

// Use it normally...
q.Where(fullExp)

It even supports full text predicate generation, so you can receive any dynamic query from an HTTP GET method, for example:

它甚至支持全文谓词生成,因此您可以从 HTTP GET 方法接收任何动态查询,例如:

var exp1 = ExpressionBuilder.CreateBinaryFromQuery<YourClass>("eq('MyProperty.Length', '5')");

var exp2 = ExpressionBuilder.CreateBinaryFromQuery<YourClass>("eq('SomeOtherProperty', 'hello')");

var fullExp = exp1.And(exp2);

// Use it normally...
q.Where(fullExp)

It supports a lot more data types and operators.

它支持更多的数据类型和运算符。

Link: https://github.com/alexmurari/Exprelsior

链接:https: //github.com/alexmurari/Exprelsior