重用lambda表达式

时间:2014-06-06 18:12:01

标签: c# linq lambda

今天我有这个重复的代码:

 public class MyProjectionExpressions
 {
    public static Expression<Func<Log, dynamic>> LogSelector()
    {
        return log => new
        {
            logId = log.LogId,
            message = log.Message,
        };
    }

    public static dynamic LogSelector(Log log)
    {
        return new
        {
            logId = log.LogId,
            message = log.Message,
        };
    }
 }

第一种方法是可重用的投影表达式,我使用如下:

    db.Logs.Select(MyProjectionExpressions.LogSelector());

当我不处理集合时使用第二种方法,但只需要一个需要序列化的项目,如下所示:

    MyProjectionExpressions.LogSelector(someLog);

我尝试重复使用代码,如下所示:

 public class MyProjectionExpressions
 {
    public static Expression<Func<Log, dynamic>> LogSelector()
    {
        return log => MyProjectionExpressions.LogSelector(log);
    }

    public static dynamic LogSelector(Log log)
    {
        return new
        {
            logId = log.LogId,
            message = log.Message,
        };
    }
 }

然而,我有“Linq-To-Entities vs Linq-To-Objects”问题,即:我必须重用我的投影表达式:

    db.Logs.ToList().Select(MyProjectionExpressions.LogSelector());

因为MyProjectionExpressions.LogSelector()现在包含(使用)Linq-To-Entities无法识别的方法:

    LINQ to Entities does not recognize the method 'MyProjectionExpressions.LogSelector()'



问题是,最后:
如何以Linq-To-Entities继续工作的方式重用lamba表达式?

这个lambda表达式:

        log => new
        {
            logId = log.LogId,
            message = log.Message,
        };

2 个答案:

答案 0 :(得分:2)

你可以这样做:

 public class MyProjectionExpressions
 {
    public static Expression<Func<Log, dynamic>> LogSelector()
    {
        return log => new
        {
            logId = log.LogId,
            message = log.Message,
        };
    }

    //Get the expression as a Func<Log, dynamic>, then apply it
    //to your log object.
    private static Func<Log, dynamic> impl = LogSelector().Compile();

    public static dynamic LogSelector(Log log)
    {
        return impl(log);
    }
 }

答案 1 :(得分:1)

不是根据编译方法实现表达式,而是根据表达式实现编译方法:

public class MyProjectionExpressions
{
    public static Expression<Func<Log, dynamic>> LogSelector()
    {
        return log => new
        {
            logId = log.LogId,
            message = log.Message,
        };
    }
    private static Lazy<Func<Log, dynamic>> func;
    static MyProjectionExpressions()
    {
        func = new Lazy<Func<Log, dynamic>>(() => LogSelector().Compile());
    }
    public static dynamic LogSelector(Log log)
    {
        return func.Value(log);
    }
}

请注意,为了避免每次需要使用时不断重新编译表达式,您可以缓存已编译的表达式并重新使用它。