5

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

我需要将它用作谓词,Expression<Func<T2, bool>>使用我试图考虑几种方法的T1属性,可能使用但无法理解它。T2Expression.Invoke

以供参考:

class T2 {
  public T1 T1;
}

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

提前非常感谢。

4

1 回答 1

7

在考虑表达式树之前,尝试使用普通 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);
}
于 2011-10-02T14:45:50.813 回答