Linq-创建表达式< T1>来自表达式< T2> [英] Linq - Creating Expression<T1> from Expression<T2>
本文介绍了Linq-创建表达式< T1>来自表达式< T2>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个谓词Expression<Func<T1, bool>>
我需要使用T2
的T1
属性将其用作谓词Expression<Func<T2, bool>>
. >
供参考:
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);
}
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.
解决方案
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);
}
这篇关于Linq-创建表达式< T1>来自表达式< T2>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文