[英]Selecting from Lambda Expression with Lambda Expression
I have two expressions: 我有两个表达:
public static Expression<Func<TSource, TReturn>> Merge<TSource, TSource2, TReturn>(
Expression<Func<TSource, TSource2>> foo1
Expression<Func<TSource2, TReturn>> foo2)
{
// What to do?
}
How can I merge them into a single expression, so the output from the first is used as the input for the second? 如何将它们合并为一个表达式,以便将第一个的输出用作第二个的输入? I am new to these and so far its just been exceptions.
我是新手,到目前为止,只是个例外。
Thanks 谢谢
This depends a lot on which providers need to use it. 这在很大程度上取决于哪些提供商需要使用它。 Some will be fine with:
有些可以使用:
public static Expression<Func<TSource, TReturn>>
Merge<TSource, TSource2, TReturn>(
Expression<Func<TSource, TSource2>> foo1,
Expression<Func<TSource2, TReturn>> foo2)
{
return Expression.Lambda<Func<TSource, TReturn>>(
Expression.Invoke(foo2, foo1.Body),
foo1.Parameters);
}
However, others (EF) will not. 但是,其他人(EF)不会。 You can also re-write the expression-tree with a visitor to inline the expression:
您还可以用访问者重写表达式树以内联表达式:
public static Expression<Func<TSource, TReturn>>
Merge<TSource, TSource2, TReturn>(
Expression<Func<TSource, TSource2>> foo1,
Expression<Func<TSource2, TReturn>> foo2)
{
var swapped = new SwapVisitor(
foo2.Parameters.Single(), foo1.Body).Visit(foo2.Body);
return Expression.Lambda<Func<TSource, TReturn>>(
swapped, foo1.Parameters);
}
class SwapVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public SwapVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
this will work with all providers. 这将适用于所有提供商。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.