tags:

views:

82

answers:

2

Hi All,

I have a method to Generate Expression By Clause as below:

internal static Expression<Func<TModel, T>> GenExpressionByClause<TModel, T>(string column)
    {
        PropertyInfo columnPropInfo = typeof(TModel).GetProperty(column);

        var entityParam = Expression.Parameter(typeof(TModel), "e");                    // {e}
        var columnExpr = Expression.MakeMemberAccess(entityParam, columnPropInfo); // {e.column}
        var lambda = Expression.Lambda(columnExpr, entityParam) as Expression<Func<TModel, T>>; // {e => e.column}
        return lambda;

    }

So I could build lambda expression as e=>e.column. but I want to change it to e=>string.Format("{0}",e.column). How could I refactor the code?

+2  A: 

This should do the work:

    internal static Expression<Func<TModel, T>> GenExpressionByClause<TModel, T>(string column)
    {
        var columnPropInfo = typeof(TModel).GetProperty(column);
        var formatMethod = typeof (string).GetMethod("Format", new[] {typeof (string), typeof (object)});

        var entityParam = Expression.Parameter(typeof(TModel), "e");
        var columnExpr = Expression.MakeMemberAccess(entityParam, columnPropInfo);
        var formatCall = Expression.Call( formatMethod, Expression.Constant("{0}"), columnExpr);
        var lambda = Expression.Lambda(formatCall , entityParam) as Expression<Func<TModel, T>>;
        return lambda;
    }

Note that you could cache the Format MethodInfo in a static field.

Romain Verdier
Excellent ~~~,thank you Romain!!
Sam Zhou
A: 

Final solution:

internal static Expression<Func<TModel, string>> GenExpressionByClauseEx<TModel>(string column)
    {
        var columnPropInfo = typeof(TModel).GetProperty(column);
        var formatMethod = typeof(String).GetMethod("Format", new[] { typeof(string), typeof(Object) });
        //string.Format(
        var entityParam = Expression.Parameter(typeof(TModel), "e");
        var columnExpr = Expression.MakeMemberAccess(entityParam, columnPropInfo);
        var columnExprObj=Expression.Convert(columnExpr, typeof(object));
        var formatCall = Expression.Call(formatMethod, Expression.Constant("111--{0}"), columnExprObj);
        var lambda = Expression.Lambda(formatCall, entityParam) as Expression<Func<TModel, string>>;
        return lambda;

    }
Sam Zhou
@Sam - your final resolution would be better placed as an update to your original question.
Sky Sanders