0

I want to create lambda expression providing property name, a value (as string) and property type (as Type).

The problem with that is in line Expression.Constant(value1, propertyType);
value1 that is passed to Foo is string. and must be parsed to "unknown" type

static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1, 
                                                     Type propertyType)
{                              
    var parameterExpression = Expression.Parameter(typeof(TheObject), "o");
    var memberExpression1 = Expression.PropertyOrField(parameterExpression, property1);

    //casting?
    var valueExpression1 = Expression.Constant(value1, propertyType);

    var binaryExpression1 = Expression.GreaterThan(memberExpression1, valueExpression1);
    return Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
}
nawfal
  • 70,104
  • 56
  • 326
  • 368
jullin
  • 633
  • 2
  • 12
  • 21

1 Answers1

0

I think you should have T where you currently have TheObject.

To convert the string, you can call the Convert.ChangeType() method in your expression and cast the resulting object:

static readonly MethodInfo ChangeTypeMethod = typeof(Convert).GetMethod(
    "ChangeType", new[] { typeof(object), typeof(Type) });

static Expression<Func<T, bool>> LabmdaExpression<T>(
    string property1, string value1, Type propertyType)
{
    ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "o");
    MemberExpression memberExpression1 = Expression.PropertyOrField(
        parameterExpression, property1);

    Expression convertedObject = Expression.Call(
        ChangeTypeMethod, Expression.Constant(value1),
        Expression.Constant(propertyType));
    Expression converted = Expression.Convert(convertedObject, propertyType);

    BinaryExpression binaryExpression1 = Expression.GreaterThan(
        memberExpression1, converted);
    return Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
}

Just casting won't work, because code like (int)"42" is not valid.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Why there is a need of Expression.Convert? – jullin Jun 19 '11 at 14:56
  • Because the return type of `Convert.ChangeType()` is `object` and you need to cast that to the actual type. You would need to do the same if you were using it directly from code. – svick Jun 19 '11 at 14:57
  • you are right, I tried this in a simple example: ` string x = "9"; int xx = (int)Convert.ChangeType(x,typeof(int));` – jullin Jun 19 '11 at 15:19