简体   繁体   中英

expression trees linq get value of a parameter?

AddOptional<tblObject>(x =>x.Title, objectToSend.SupplementaryData);

private static void AddOptional<TType>(Expression<Func<TType,string>> expr, Dictionary<string, string> dictionary)
{
    string propertyName;
    string propertyValue;

    Expression expression = (Expression)expr;
    while (expression.NodeType == ExpressionType.Lambda)
    {
        expression = ((LambdaExpression)expression).Body;
    }
}

In Above code i would like to get actual value of property title, not ony propert name , is it possible ?

private static void Main(string[] args)
{
    CompileAndGetValue<tblObject>(x => x.Title, new tblObject() { Title =  "test" });
}

private static void CompileAndGetValue<TType>(
    Expression<Func<TType, string>> expr,
    TType obj)
{
    // you can still get name here

    Func<TType, string> func = expr.Compile();
    string propretyValue = func(obj);
    Console.WriteLine(propretyValue);
}

However, you must be aware that this can be quite slow. You should measure how it performs in your case.

If you don't like to pass your object:

    private static void Main(string[] args)
    {
        var yourObject = new tblObject {Title = "test"};
        CompileAndGetValue(() => yourObject.Title);
    }


    private static void CompileAndGetValue(
        Expression<Func<string>> expr)
    {
        // you can still get name here

        var func = expr.Compile();
        string propretyValue = func();
        Console.WriteLine(propretyValue);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM