我有一个谓词 Expression<Func<T1, bool>>
我需要将它用作谓词 Expression<Func<T2, bool>>
使用 T1
T2
的属性(property)我试图考虑几种方法,可能使用 Expression.Invoke
但无法理解它。
供引用:
class T2 {
public T1 T1;
}
和
Expression<Func<T1, bool>> ConvertPredicates(Expression<Func<T2, bool>> predicate) {
//what to do here...
}
非常感谢。
最佳答案
在考虑表达式树之前,尝试使用普通 lambda 找到解决方案。
你有一个谓词
Func<T1, bool> p1
想要一个谓词
Func<T2, bool> p2 = (x => p1(x.T1));
您可以将其构建为表达式树,如下所示:
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);
}
关于c# - Linq - 从表达式 <T2> 创建表达式 <T1>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7626965/