[英]How to build () => x.prop lambda expression dynamically?
I have code like 我的代码就像
DepartmentPaperConsumption dto = null;
then later i have NHibernate QueryOver result, and i want to order it 然后我有NHibernate QueryOver结果,我想订购它
result.OrderByAlias(() => dto.TotalColorCopys);
but I want to be able to specify any property of dto
dynamicly with string. 但我希望能够用字符串动态地指定dto
任何属性。 I tryed using Dynamic LINQ but is seems that I just can't get it. 我尝试使用动态LINQ,但似乎我无法得到它。 I also tried building LambdaExpression from ground up - also without luck. 我也试过从头开始构建LambdaExpression - 也没有运气。 I would appreciate any help. 我将不胜感激任何帮助。
You can see how to construct the lambda here , but it really is pretty simple in your case: 你可以在这里看到如何构造lambda,但在你的情况下它真的很简单:
var arg = Expression.Constant(null, typeof(DepartmentPaperConsumption));
var body = Expression.Convert(Expression.PropertyOrField(arg, propertyName),
typeof(object));
var lambda = Expression.Lambda<Func<object>>(body);
The tricky thing is invoking the OrderByAlias
- using MakeGenericMethod
may be the way, as shown in the link above. 棘手的是调用OrderByAlias
- 使用MakeGenericMethod
可能就是这样,如上面的链接所示。
well use dynamic linq as you wrote, or use expression tree http://msdn.microsoft.com/en-us/library/bb397951.aspx 好好用你编写的动态linq,或者使用表达式树http://msdn.microsoft.com/en-us/library/bb397951.aspx
i don't think that there are other solutions 我不认为还有其他解决方案
I managed to find one way myself, but it looks more of workaround, Marc's version is way more simpler. 我自己设法找到了一种方法,但它看起来更像是解决方法,Marc的版本更简单。 I will accept Marc's answer as soon as i will test it. 我会在测试后立即接受Marc的回答。 Heres my workaround : 继承人我的解决方法:
public class MemberModifier : ExpressionVisitor
{
public Expression Modify(Expression expression)
{
return Visit(expression);
}
protected override Expression VisitMember(MemberExpression node)
{
var t = typeof (DepartmentPaperConsumption);
var memberInfo = t.GetMember("TotalPages")[0];
return Expression.MakeMemberAccess(node.Expression, memberInfo);
}
}
and then in code 然后在代码中
Expression<Func<object>> exp = () => dto.TotalColorPrints;
var mod = new MemberModifier();
var modEx = mod.Modify(exp);
result.OrderByAlias((Expression<Func<object>>)modEx)
MemberModifier is only raw prototype, it should be more generic and not depend on DepartmentConsumption and without hardcoded "TotalPages" MemberModifier只是原始原型,它应该更通用,不依赖于DepartmentConsumption,也没有硬编码的“TotalPages”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.