C# - 使用属性名称作为字符串按属性排序的代码 [英] C# - code to order by a property using the property name as a string

查看:30
本文介绍了C# - 使用属性名称作为字符串按属性排序的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将属性名称作为字符串时,在 C# 中针对属性进行编码的最简单方法是什么?例如,我希望允许用户通过他们选择的属性(使用 LINQ)对某些搜索结果进行排序.他们会选择order by"UI 中的属性 - 当然是作为字符串值.有没有办法直接将该字符串用作 linq 查询的属性,而不必使用条件逻辑(if/else、switch)将字符串映射到属性.反思?

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 TypeDescriptors 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆