当属性名是字符串时,在 C # 中针对属性编写代码最简单的方法是什么?例如,我希望允许用户根据他们选择的属性(使用 LINQ)来订购一些搜索结果。他们将在 UI 中选择“ order by”属性——当然是字符串值。有没有一种方法可以直接使用该字符串作为 linq 查询的属性,而不必使用条件逻辑(if/else,switch)将字符串映射到属性。反射?
从逻辑上讲,这是我想要做的:
query = query.OrderBy(x => x."ProductId");
更新:
我最初并没有指定使用 Linq to Entities
——看起来反射(至少是 GetProperty,GetValue 方法)并没有转换成 L2E。