什么是最简单的方法code反对在C#中的属性时,我有属性的字符串名字?例如,我想允许用户通过他们的选择(使用LINQ)的属性来订购一些搜索结果。他们会选择属性在用户界面中排序依据 - 当然字符串值。有没有一种方法可以直接使用该字符串作为LINQ查询的性能,而不必使用条件逻辑(的if / else,开关)的字符串映射到属性。反思?
What's the simplest way to code against a property in C# when I have the property name as a string? For example, I want to allow the user to order some search results by a property of their choice (using LINQ). They will choose the "order by" property in the UI - as a string value of course. Is there a way to use that string directly as a property of the linq query, without having to use conditional logic (if/else, switch) to map the strings to properties. Reflection?
从逻辑上讲,这就是我想要做的:
Logically, this is what I'd like to do:
query = query.OrderBy(x => x."ProductId");
更新: 我最初没有指定我使用LINQ到实体 - 看起来反射(至少使用getProperty,的GetValue方法)并没有转化为L2E
Update: I did not originally specify that I'm using Linq to Entities - it appears that reflection (at least the GetProperty, GetValue approach) does not translate to L2E.
我会提供这种替代其他人都已经发布。
I would offer this alternative to what everyone else has posted.
System.Reflection.PropertyInfo prop = typeof(YourType).GetProperty("PropertyName");
query = query.OrderBy(x => prop.GetValue(x, null));
这可以避免重复调用反射API获得的财产。现在唯一的重复调用获得的价值。
This avoids repeated calls to the reflection API for obtaining the property. Now the only repeated call is obtaining the value.
然而
我会主张使用的PropertyDescriptor
代替,因为这将允许自定义 TypeDescriptor
s到分配给你的键入,从而可以有轻量的操作:获取属性和值。在没有定制的描述符,将回落到反射无论如何。
I would advocate using a PropertyDescriptor
instead, as this will allow for custom TypeDescriptor
s to be assigned to your type, making it possible to have lightweight operations for retrieving properties and values. In the absence of a custom descriptor it will fall back to reflection anyhow.
PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(YourType)).Find("PropertyName");
query = query.OrderBy(x => prop.GetValue(x));
至于加速起来,看看马克碎石的HyperDescriptor项目于$ C $的CProject。我用这个大获成功;这是一个生命的救星为高性能数据绑定和动态性操作的业务对象。
As for speeding it up, check out Marc Gravel's HyperDescriptor
project on CodeProject. I've used this with great success; it's a life saver for high-performance data binding and dynamic property operations on business objects.