Linq - 从表达式<T2>创建表达式<T1>

Var*_*ant 5 c# linq predicate linq-expressions

我有一个谓词 Expression<Func<T1, bool>>

我需要使用它作为谓词Expression<Func<T2, bool>>使用我试图考虑几个approches 的T1属性T2,可能使用Expression.Invoke但couln; t让我的头围绕它.

以供参考:

class T2 {
  public T1 T1;
}
Run Code Online (Sandbox Code Playgroud)

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

非常感谢提前.

dtb*_*dtb 7

在考虑表达式树之前,尝试使用普通的lambda找到解决方案.

你有一个谓词

Func<T1, bool> p1
Run Code Online (Sandbox Code Playgroud)

并想要一个谓词

Func<T2, bool> p2 = (x => p1(x.T1));
Run Code Online (Sandbox Code Playgroud)

您可以将其构建为表达式树,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)