有没有办法更容易地结合表达式和lambda?

时间:2016-08-03 06:06:32

标签: c# linq linq-to-entities linq-expressions

假设我有Expression<Func<Foo, Bar>> calculateBarBar“缩减”为Foo,我可以这样使用:

IQueryable foo = getFoos();
bars = foo.Select(calculateBar);

但是,我有时需要能够引用输入Foo,所以我想包装calculateBar以便它可以返回Tuple<Foo, Bar>

public static Expression<Func<TIn, Tuple<TIn, TOut>>> WithInput<TIn, TOut>(
    this Expression<Func<TIn, TOut>> expression)
{
    var param = Expression.Parameter(typeof(TIn));
    var constructor = typeof(Tuple<TIn, TOut>).GetConstructor(new[] { typeof(TIn), typeof(TOut) });

    if (constructor == null) throw new ArgumentNullException();

    return Expression.Lambda<Func<TIn, Tuple<TIn, TOut>>>(Expression.New(constructor, param, Expression.Invoke(expression, param)), param);
}

现在,该功能在实践中运行良好。但是,在LINQ-to-Entities中,构造函数必须是无参数的。所以,相反,我可能想要创建一个假的元组(new WithInput<Foo, Bar> { Input = theFoo, Output = theBar }),但把它作为一个表达式来写会相当痛苦。

有没有办法使用Lambda构建现有表达式(不会扰乱LINQ-to-Entities),而不是继续构建更多Expression树?

例如(伪代码):

Expression<Func<Foo, WithInput<Foo, Bar>>> wrapper = foo => new WithInput { Input = foo, Output = Expression.Invoke(calculateBar, foo) };

1 个答案:

答案 0 :(得分:1)

Tuple相比,写MemberInit表达式并不那么痛苦。只是为了记录,它将是这样的:

public static Expression<Func<TIn, WithInput<TIn, TOut>>> WithInput<TIn, TOut>(
    this Expression<Func<TIn, TOut>> expression)
{
    var parameter = expression.Parameters[0];
    var resultType = typeof(WithInput<TIn, TOut>);
    var body = Expression.MemberInit(Expression.New(resultType),
        Expression.Bind(resultType.GetProperty("Input"), parameter),
        Expression.Bind(resultType.GetProperty("Output"), expression.Body));
    return Expression.Lambda<Func<TIn, WithInput<TIn, TOut>>>(body, parameter);
}

现在主题。如果不使用某些自定义表达式处理实用程序库(您自己的或第三方),则无法基于现有的lambda构建表达式。

例如,LINQKit提供了InvokeExpand扩展方法,可以像这样使用:

using LinqKit;

public static Expression<Func<TIn, WithInput<TIn, TOut>>> WithInput<TIn, TOut>(
    this Expression<Func<TIn, TOut>> expression)
{
    return Linq.Expr((TIn input) => new WithInput<TIn, TOut>
    {
        Input = input,
        Output = expression.Invoke(input)
    }).Expand();
}
相关问题