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

标签 c# linq predicate linq-expressions

我有一个谓词 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/

相关文章:

c# - 如何将 XML 数据解析为自定义 C# 类的属性?

c# - 比较出错 c# Dictionary<String, string[]>

ios - 等价查询 MagicalRecord -> Realm.io

c++ - STL 从 vector 中删除与谓词匹配的第一个元素

c# - 文件保存选取器 - 保存编辑后的图像(C# Metro 应用程序)

c# - 绑定(bind)到 ItemsControl ItemTemplate 内的 TextBox

c# - 将 linq 方法语法转换为查询语法

swift - 如何编写 NSPredicate 来搜索一对多关系的日期属性?

c# - ECDSA 登录 c# 在 c 中验证

c# - Math.Net Numerics - 拟合正弦函数