Search code examples
c#.netlinqlambdaexpression-trees

How to get the value of an expression


I have this function that uses Linq expressions:

private Expression GetFieldValueExpression(ParameterExpression parameter, string fieldName)
{
  Expression properyIndexExpression = System.Linq.Expressions.Expression.Constant (fieldName, typeof(string));
  IndexExpression fieldValueExpression = System.Linq.Expressions.Expression.Property(parameter, "Item", new Expression[] { properyIndexExpression });
  return Expression.Property(fieldValueExpression, "Value");
}

The value returned by Expression.Property(fieldValueExpression, "Value") is of type string.

I don't know how to get it. I know that i must create a lambda and compile it, but i don't know how.

Thank you for your time.


Solution

  • Perhaps you are looking for code like this:

        public void EvaluateAnExpression()
        {
            //Make the parameter
            var parm = Expression.Parameter(typeof(TestClass),"parm");
    
            //Use your method to build the expression
            var exp = GetFieldValueExpression(parm, "testField");
    
            //Build a lambda for the expression
            var lambda = Expression.Lambda(exp, parm);
    
            //Compile the lamda and cast the result to a Func<>
            var compiled = (Func<TestClass, string>)lambda.Compile();
    
            //We'll make up some object to test on
            var obj = new TestClass();
    
            //Get the result (it will be TESTFIELD)
            var result = compiled(obj);
        }
    

    that code assumes some test classes that look like this (basically the indexer property just returns the input but in upper case - a trivial example but works for testing):

        public class TestClass
        {
            public InnerClass this[string indexParameter]
            {
                get
                {
                    return new InnerClass { Value = indexParameter.ToUpper() };
                }
            }
        }
    
        public class InnerClass
        {
            public string Value { get; set; }
        }