包括调用 Enumerable.Select 的子表达式树
本文关键字:表达式 Select 调用 Enumerable 包括 | 更新日期: 2023-09-27 18:37:16
我想使用一个lambda表达式作为Enumerable.Select方法的参数,并将其作为新绑定添加到父lambda表达式中,如下所示:
Expression<Func<Bar, BarDto>> MapBar = b => new BarDto { BarInt = b.BarInt };
Expression<Func<Foo, FooDto>> MapFoo = f => new FooDto { FooInt = f.FooInt };
Expression<Func<Foo, FooDto>> expressionIWant = f => new FooDto
{
FooInt = f.FooInt,
Bars = f.Bars.Select(b => new BarDto { BarInt = b.BarInt })
};
到目前为止,我到达的地方:
我有一个表达式访问者包含:
protected override Expression VisitMemberInit(MemberInitExpression node)
{
var newBindings = new[]
{
Expression.Bind(_pi, _newExpr),
};
node = node.Update(
node.NewExpression,
node.Bindings.Concat(newBindings));
return node;
}
我显然需要包含类似以下内容的内容
var typeArgs = _originalChildExpression.Type.GenericTypeArguments;
_newExpr = Expression.Call(typeof(Enumerable),"Select",typeArgs,???source???,
_originalChildExpression);
哪里???源???表示顶部expressionIWant
中的f.Bars
。如何实现这一点?谢谢。
这与你之前的问题非常相似。看
Expression<Func<Foo, FooDto>> expressionIWant = f => new FooDto
{
FooInt = f.FooInt,
Bars = f.Bars.Select(b => new BarDto { BarInt = b.BarInt })
};
你可以看到f.Bars
是Parameter("f")
的Property("Bars")
。
因此,整个方法可能是这样的:
public static class ExpressionUtils
{
public static Expression<Func<T, TMap>> AddCollectionMap<T, TMap, U, UMap>(
this Expression<Func<T, TMap>> parent,
Expression<Func<U, UMap>> nav,
string propName)
{
var parameter = parent.Parameters[0];
var target = typeof(TMap).GetProperty(propName);
var source = Expression.Property(parameter, propName);
var binding = Expression.Bind(target, Expression.Call(
typeof(Enumerable), "Select", nav.Type.GenericTypeArguments, source, nav));
var body = parent.Body.AddMemberInitBindings(binding);
return Expression.Lambda<Func<T, TMap>>(body, parameter);
}
static Expression AddMemberInitBindings(this Expression expression, params MemberBinding[] bindings)
{
return new AddMemberInitBindingsVisitor { Bindings = bindings }.Visit(expression);
}
class AddMemberInitBindingsVisitor : ExpressionVisitor
{
public MemberBinding[] Bindings;
protected override Expression VisitMemberInit(MemberInitExpression node)
{
return node.Update(node.NewExpression, node.Bindings.Concat(Bindings));
}
}
}
和示例用法:
var expressionIGet = MapFoo.AddCollectionMap(MapBar, "Bars");