Combining two expressions (Expression>)

前端 未结 7 1532
无人共我
无人共我 2020-11-22 01:09

I have two expressions of type Expression> and I want to take to OR, AND or NOT of these and get a new expression of the same type

相关标签:
7条回答
  • 2020-11-22 01:59

    I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.

    The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.

    public IQueryable<UbezpExt> UbezpFull
    {
        get
        {
            System.Linq.Expressions.Expression<
                Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
                (u, parAdrM, parAdrZ) => new UbezpExt
                {
                    Ub = u,
                    AdrM = parAdrM,
                    AdrZ = parAdrZ,
                };
    
            // From here an expression builder ExprAdres is called.
            var expr2 = expr
                .ReplacePar("parAdrM", ExprAdres("M").Body)
                .ReplacePar("parAdrZ", ExprAdres("Z").Body);
            return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
        }
    }
    

    And this is the subexpression building code:

    public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
    {
        return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
            .OrderByDescending(a => a.DATAOD).FirstOrDefault();
    }
    

    What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.

    0 讨论(0)
提交回复
热议问题