none
How to get a closure value from Lambda Expression? RRS feed

  • Question

  • string p ="1" ;
    Expression<Func<PLY_BASE, bool>> exp = c =>c.VIP_FLAG==p;

    MyMethod(LambdaExpression exp)

    {

    var expr = exp.Body as BinaryExpression;
    var obj = expr.Right as System.Linq.Expressions.MemberExpression;
    var value = (obj.Expression as ConstantExpression).Value;

    //here, value is a closure type of something like {.DisplayClass}

    how can I get the real value and use it?

    }


    they say nothing last forever

    Sunday, July 22, 2012 2:09 PM

Answers

  • p is a variable, when the where method translate to sql, the "p" will be replaced by the real value. We couldn't get the parameter's value from a lambda expression. For Expression, we can create "ParameterExpression" for parameters, "ConstantExpression" for constant. In your code, you can create a ConstantExpression for "p".
    Monday, July 30, 2012 8:59 AM

All replies

  • Hi del.piero,

    Welcome to MSDN Forum.

    I'm not clear about the 'closure type', could you please clarify what's the function you want to realize?

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Tuesday, July 24, 2012 7:22 AM
    Moderator
  • Hi,

    in Mymethod, I will receive a lambda expression like this:

    string p ="1" ;
    Expression<Func<PLY_BASE, bool>> exp = c =>c.VIP_FLAG==p;
    MyMethod(exp);

    public void MyMethod(LambdaExpression exp)

    {

    //I want to get the value of parameter "p", which is "1".

    }


    they say nothing last forever

    Tuesday, July 24, 2012 7:54 PM
  • Hi del.piero,

    Sorry, I still don't understand what's your purpose. "p" is a variable, you can just call it to get the value, why you want to get the value from LambdaExpression? 

    By the way, I've found some of your previous posts are in Chinese, here's a good article about Expression Tree in Chinese, I hope it could help.

    http://www.cnblogs.com/ninputer/archive/2009/08/28/expression_tree1.html

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us



    Thursday, July 26, 2012 8:14 AM
    Moderator
  • Of course I can pass one more parameter to the method, but I just want to know whether it is possible to get value from Lambda itself.

    See, if I use entity framework, write something like this:

    string p ="1" ;

    Dbcontext.Set<Table>.Where(x=>x.column==p).FirstorDefault();

    how does EF generate the SQL statement from this "Where"?


    they say nothing last forever

    Friday, July 27, 2012 4:24 PM
  • p is a variable, when the where method translate to sql, the "p" will be replaced by the real value. We couldn't get the parameter's value from a lambda expression. For Expression, we can create "ParameterExpression" for parameters, "ConstantExpression" for constant. In your code, you can create a ConstantExpression for "p".
    Monday, July 30, 2012 8:59 AM