使用反射从属性名称获取 lambda 表达式 [英] Use reflection to get lambda expression from property Name
问题描述
我想让用户可以选择按不同的属性进行搜索.例如
I want to give the user the choice of searching by different properties. For instance
[输入文本] |[选择选项{ID、姓名、电话}] |[搜索]
[INPUT TEXT] | [SELECT OPTION {ID, NAME, PHONE}] | [SEARCH]
我稍后会像这样构建我的查询:
And I would later build my query like this:
repository.Where(lambda-expression)
从所选选项 {ID, NAME, PHONE} 构建 lambda 表达式的地方(例如:x => x.NAME.Equals(INPUT TEXT))
Where lambda-expression is build from the selected option {ID, NAME, PHONE} (For example: x => x.NAME.Equals(INPUT TEXT))
是否可以使用反射从属性名称构建 lambda?
Is there a way to build the lambda from the Property name perhaps using reflection?
谢谢
推荐答案
您无需构建 lambda 表达式 - 您构建的是表达式树.这并不难,但需要一点耐心.在您的示例中,您可能需要:
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);
假设:
- 存储库元素类型为
Foo
- 您想使用名为
propertyName
的属性 - 您想与
inputText
比较是否相等
- The repository element type is
Foo
- You want to use a property called
propertyName
- You want to compare for equality against
inputText
这篇关于使用反射从属性名称获取 lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!