出于我的项目的目的,我需要对一个权限进行一些linq查询,我使用表达式工厂方法来构建动态过滤谓词。
考虑此代码:
public class mother{
public int age {get; set;}
public string name {get; set;}
public child child {get; set;}
}
public class child{
public int age {get; set;}
public string name {get; set;}
}
//predicate builder
public static Expression<Func<T, bool>> GetChildNamePredicat<T>(){
var param = Expression.Parameter(typeof(T), "param");
// age property of mother class
var motherAgeProperty = Expression.MakeMemberAccess(param, typeof(T).GetProperty("age"));
// name property of child class
var motherChildProperty = Expression.MakeMemberAccess(param, typeof (t).GetProperty("child"));
var childNameProperty = Expression.MakeMemberAccess(motherChildProperty , typeof (child).GetProperty("name "));
BinaryExpression motherAgeCondition;
BinaryExpression childNameCondition;
//building condition mother age >= 40 and child name = junior
var motherAgeConst = Expression.Constant(40, typeof(int));
var childNameConst = Expression.Constant("junior", typeof(string));
motherAgeCondition = Expression.GreaterThanOrEqual(motherAgeProperty, motherAgeConst);
childNameCondition= Expression.Equal(childNameProperty, childNameConst);
var mergeCondition = Expression.AndAlso(motherAgeCondition , childNameCondition);
//return expression
return Expression.Lambda<Func<T, bool>>(mergeCondition , param);
}
var myPredicate = GetChildNamePredicat<mother>();
此代码编译成功,但似乎不是fonctionnal,没有结果...... 通过在“myPredicate”上使用变量的间谍,我可以看到这样的lambda调试视图:
.Lambda
#Lambda1<System.Func`2[myNameSpace.mother,System.Boolean]>(myNameSpace.mothe $e) { $e.age >= 40 && ($e.child).name == "junior" }
($ e.child)......太奇怪了
您是否知道另一个解决方案或/并且想知道从母参数访问子名称属性?
提前谢谢!