使用C#中的string.format生成lambda Expression By Clause?

时间:2010-03-09 10:11:29

标签: c# lambda

我有一个生成Expression By Clause的方法如下:

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;

    }

所以我可以将lambda表达式构建为e=>e.column。 但我想将其更改为e=>string.Format("{0}",e.column)。我怎么能重构代码?

2 个答案:

答案 0 :(得分:3)

这应该做的工作:

    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;
    }

请注意,您可以将Format MethodInfo缓存在静态字段中。

答案 1 :(得分:0)

最终解决方案:

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;

    }