加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将两个表达式组合成一个管道

发布时间:2020-12-15 23:36:09 所属栏目:百科 来源:网络整理
导读:我们假设我有以下两种表达方式: ExpressionFuncT,IEnumerableTNested collectionSelector;ExpressionFuncIEnumerableTNested,TNested elementSelector; 有没有办法“组合”这些以形成以下:(?) ExpressionFuncT,TNested selector; 编辑: 性能非常关键,所以
我们假设我有以下两种表达方式:

Expression<Func<T,IEnumerable<TNested>>> collectionSelector;
Expression<Func<IEnumerable<TNested>,TNested>> elementSelector;

有没有办法“组合”这些以形成以下:(?)

Expression<Func<T,TNested>> selector;

编辑:

性能非常关键,所以如果可能的话,我会很高兴能够以极少的开销实现最佳解决方案.

非常感谢!

解决方法

static Expression<Func<A,C>> Foo<A,B,C>(
Expression<Func<B,C>> f,Expression<Func<A,B>> g)
{
    var x = Expression.Parameter(typeof(A));
    return Expression.Lambda<Func<A,C>>(
        Expression.Invoke(f,Expression.Invoke(g,x)),x);
}

不幸的是,我无法访问计算机(这在性能方面是不好的解决方案).实际上,我认为您可以通过调用Expression来优化代码.

另一种方式似乎是(使用辅助功能):

Func<A,C> Foo<A,C>(Func<B,C> f,Func<A,B> g)
{ 
    return (A x) => f(g(x));
}

然后你应该通过调用带有Foo函数的Expression来创建管道表达式.像那个伪代码:

var expr1 = get expresstion<B,C> 
   var expr2 = get Expression<A,B>
   var foo = get method info of Foo method 
   specialize method with generic types A,C (via make generic method)
    return Expression.Call(foo,expr1,expr2);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读