问题描述
我想给用户通过不同的属性搜索的选择。例如
I want to give the user the choice of searching by different properties. For instance
[输入文本] | [选择选项{ID,姓名,电话}] | [SEARCH]
[INPUT TEXT] | [SELECT OPTION {ID, NAME, PHONE}] | [SEARCH]
和我以后会建立我的查询是这样的:
And I would later build my query like this:
repository.Where(lambda-expression)
其中的λ-EX pression从所选的选项,打造{ID,姓名,电话}
(例如:X => x.NAME.Equals(输入文本))
Where lambda-expression is build from the selected option {ID, NAME, PHONE}(For example: x => x.NAME.Equals(INPUT TEXT))
有没有建在属性名拉姆达可能使用反射的方式?
Is there a way to build the lambda from the Property name perhaps using reflection?
感谢
推荐答案
您不建立一个lambda前pression - 您打造一个前pression树。这是不是非常难,但需要一点耐心。在您的样品你可能需要:
You don't build a lambda expression - you build an expression tree. It's not terribly hard, but it takes a little patience. In your sample you'd probably need:
ParameterExpression parameter = Expression.Parameter(typeof(Foo), "x");
Expression property = Expression.Property(parameter, propertyName);
Expression target = Expression.Constant(inputText);
Expression equalsMethod = Expression.Call(property, "Equals", null, target);
Expression<Func<Foo, bool>> lambda =
Expression.Lambda<Func<Foo, bool>>(equalsMethod, parameter);
这是假设:
- 存储库元素类型是
富
- 您想使用一个名为属性
propertyName的
- 您想比较反对
的inputText
平等
- The repository element type is
Foo
- You want to use a property called
propertyName
- You want to compare for equality against
inputText
这篇关于使用反射来物业名称获得拉姆达前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!