如何在不调用的情况下合并两个 C# Lambda 表达式?

发布于 2024-07-27 21:24:23 字数 668 浏览 4 评论 0原文

我想合并以下表达式:

// example class
class Order
{
    List<OrderLine> Lines       
}
class OrderLine { }

Expression<Func<Order, List<OrderLine>>> selectOrderLines = o => o.Lines;
Expression<Func<List<OrderLine>, Boolean>> validateOrderLines = lines => lines.Count > 0;

// now combine those to
Expression<Func<Order, Boolean>> validateOrder;

我使用 selectOrderLines 上的调用并将结果提供给 validateOrderLines 使其工作,但因为我在实体框架中使用这些表达式,所以我必须实际创建一个干净的表达式应该代表:

Expression<Func<Order, Boolean>> validateOrder = o => o.Lines.Count > 0;

我该怎么做?

I'd like to merge the following Expressions:

// example class
class Order
{
    List<OrderLine> Lines       
}
class OrderLine { }

Expression<Func<Order, List<OrderLine>>> selectOrderLines = o => o.Lines;
Expression<Func<List<OrderLine>, Boolean>> validateOrderLines = lines => lines.Count > 0;

// now combine those to
Expression<Func<Order, Boolean>> validateOrder;

I got it to work using a invoke on the selectOrderLines and supplying the result to the validateOrderLines, but because I'm using these expressions in Entity Framework, I have to actually create a clean expression which should represent:

Expression<Func<Order, Boolean>> validateOrder = o => o.Lines.Count > 0;

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

佞臣 2024-08-03 21:24:23

最优雅的方法是使用 表达式访问者。 特别是,这个MSDN 博客条目 描述了如何使用它来组合谓词(使用布尔 And 或 Or)而不使用 Invoke。

已编辑 意识到布尔组合不是您想要的,我编写了一个 ExpressionVisitor 的示例用法来解决您的特定问题:

public class ParameterToMemberExpressionRebinder : ExpressionVisitor
{
    ParameterExpression _paramExpr;
    MemberExpression _memberExpr;

    ParameterToMemberExpressionRebinder(ParameterExpression paramExpr, MemberExpression memberExpr) 
    {
        _paramExpr = paramExpr;
        _memberExpr = memberExpr;
    }

    protected override Expression Visit(Expression p)
    {
        return base.Visit(p == _paramExpr ? _memberExpr : p);
    }

    public static Expression<Func<T, bool>> CombinePropertySelectorWithPredicate<T, T2>(
        Expression<Func<T, T2>> propertySelector,
        Expression<Func<T2, bool>> propertyPredicate)
    {
        var memberExpression = propertySelector.Body as MemberExpression;

        if (memberExpression == null)
        {
            throw new ArgumentException("propertySelector");
        }

        var expr = Expression.Lambda<Func<T, bool>>(propertyPredicate.Body, propertySelector.Parameters);
        var rebinder = new ParameterToMemberExpressionRebinder(propertyPredicate.Parameters[0], memberExpression);
        expr = (Expression<Func<T, bool>>)rebinder.Visit(expr);

        return expr;
    }

    class OrderLine
    {
    }

    class Order
    {
        public List<OrderLine> Lines;
    }

    static void test()
    {
        Expression<Func<Order, List<OrderLine>>> selectOrderLines = o => o.Lines;
        Expression<Func<List<OrderLine>, Boolean>> validateOrderLines = lines => lines.Count > 0;
        var validateOrder = ParameterToMemberExpressionRebinder.CombinePropertySelectorWithPredicate(selectOrderLines, validateOrderLines);

        // validateOrder: {o => (o.Lines.Count > 0)}
    }
}

The most elegant way is to use an Expression Visitor. In particular, this MSDN Blog Entry describes how to use it to combine predicates (using boolean And or Or) without Invoke.

EDITED Having realized boolean combination is not what you wanted, I wrote a sample usage of ExpressionVisitor that solves for your particular problem:

public class ParameterToMemberExpressionRebinder : ExpressionVisitor
{
    ParameterExpression _paramExpr;
    MemberExpression _memberExpr;

    ParameterToMemberExpressionRebinder(ParameterExpression paramExpr, MemberExpression memberExpr) 
    {
        _paramExpr = paramExpr;
        _memberExpr = memberExpr;
    }

    protected override Expression Visit(Expression p)
    {
        return base.Visit(p == _paramExpr ? _memberExpr : p);
    }

    public static Expression<Func<T, bool>> CombinePropertySelectorWithPredicate<T, T2>(
        Expression<Func<T, T2>> propertySelector,
        Expression<Func<T2, bool>> propertyPredicate)
    {
        var memberExpression = propertySelector.Body as MemberExpression;

        if (memberExpression == null)
        {
            throw new ArgumentException("propertySelector");
        }

        var expr = Expression.Lambda<Func<T, bool>>(propertyPredicate.Body, propertySelector.Parameters);
        var rebinder = new ParameterToMemberExpressionRebinder(propertyPredicate.Parameters[0], memberExpression);
        expr = (Expression<Func<T, bool>>)rebinder.Visit(expr);

        return expr;
    }

    class OrderLine
    {
    }

    class Order
    {
        public List<OrderLine> Lines;
    }

    static void test()
    {
        Expression<Func<Order, List<OrderLine>>> selectOrderLines = o => o.Lines;
        Expression<Func<List<OrderLine>, Boolean>> validateOrderLines = lines => lines.Count > 0;
        var validateOrder = ParameterToMemberExpressionRebinder.CombinePropertySelectorWithPredicate(selectOrderLines, validateOrderLines);

        // validateOrder: {o => (o.Lines.Count > 0)}
    }
}
晨敛清荷 2024-08-03 21:24:23

此扩展有效:

public static class Utility
    {
        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)
            var 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
            var 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);
        }
    }

示例使用:

Expression<Func<Product, bool>> filter1 = p => a.ProductId == 1;
Expression<Func<Product, bool>> filter2 = p => a.Text.StartWith("test");
Expression<Func<Product, bool>> filterCombined = filter1.And(filter2);

This extension works:

public static class Utility
    {
        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)
            var 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
            var 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);
        }
    }

Sample using:

Expression<Func<Product, bool>> filter1 = p => a.ProductId == 1;
Expression<Func<Product, bool>> filter2 = p => a.Text.StartWith("test");
Expression<Func<Product, bool>> filterCombined = filter1.And(filter2);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文