Linq - Creating Expression<T1> from Expression<T2>

对着背影说爱祢 提交于 2019-12-10 14:29:42

问题


I have a predicate Expression<Func<T1, bool>>

I need to use it as a predicate Expression<Func<T2, bool>> using the T1 property of T2 I was trying to think about several approches, probably using Expression.Invoke but couln;t get my head around it.

For reference:

class T2 {
  public T1 T1;
}

And

Expression<Func<T1, bool>> ConvertPredicates(Expression<Func<T2, bool>> predicate) {
  //what to do here...
}

Thanks a lot in advance.


回答1:


Try to find the solution with normal lambdas before you think about expression trees.

You have a predicate

Func<T1, bool> p1

and want a predicate

Func<T2, bool> p2 = (x => p1(x.T1));

You can build this as an expression tree as follows:

Expression<Func<T2, bool>> Convert(Expression<Func<T1, bool>> predicate)
{
    var x = Expression.Parameter(typeof(T2), "x");
    return Expression.Lambda<Func<T2, bool>>(
        Expression.Invoke(predicate, Expression.PropertyOrField(x, "T1")), x);
}


来源:https://stackoverflow.com/questions/7626965/linq-creating-expressiont1-from-expressiont2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!