Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

c# - Combine two lambda expressions with inner expression

I have the next class structure:

    public class Order
    {
        public User User { get; set; }
        public string Name { get; set; }
    }

    public class Authentication
    {
        public string Email { get; set; }      
    }

    public class User
    {
        public string Name { get; set; }
        public List<Authentication> Auths { get; set; }
    }

I'm trying to build an expression at runtime to search entities by User.Name, Order.Name or User.Auths.Email

There are three expressions I'm trying to combine:

    Expression<Func<Order, bool>> usernameExpression = order => order.Name.Contains(searchValue);
    Expression<Func<Order, bool>> nameExpression = order => order.User.Name.Contains(searchValue);
    Expression<Func<Order, bool>> emailExpression = order => order.User.Auths.Any(auth => auth.Email.Contains(searchValue));

I successfully combined two first expressions using ParameterReplacer from this thread: How to Combine two lambdas

However, when combining resulting expression with email expression I get the next error:

Property 'System.String Email' is not defined for type Order'

Looks like the scope doesn't know anything about inner 'auth' parameter. Is it possible to creeate the expression without rebuilding it from scratch?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ParameterReplacer you have used is too simplified and blindly replaces every parameter.

Use this instead:

public static class ExpressionUtils
{
    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
    {
        return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
    }

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node)
        {
            return node == Source ? Target : base.VisitParameter(node);
        }
    }
}

Or use this or this predicate builder helpers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...