C#-使用属性名称作为字符串按属性排序的代码 [英] C# - code to order by a property using the property name as a string
问题描述
当我将属性名称作为字符串时,对C#中的属性进行编码的最简单方法是什么?例如,我想允许用户通过他们选择的属性(使用LINQ)对一些搜索结果进行排序.他们将在UI中选择"order by"属性-当然是字符串值.有没有一种方法可以直接使用该字符串作为linq查询的属性,而不必使用条件逻辑(如果/否则,切换)将字符串映射到属性.反思?
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 to Entities-看来反射(至少是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
分配给您的类型,从而可以进行轻量级的操作来检索属性和值.在缺少自定义描述符的情况下,无论如何它都会退回去反映.
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));
要加快速度,请查看Marc Gravel的 HyperDescriptor
项目在CodeProject上.我已经成功地使用了它;它是针对业务对象进行高性能数据绑定和动态属性操作的救生器.
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.
这篇关于C#-使用属性名称作为字符串按属性排序的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!