当我将属性名称作为字符串时,对C#中的属性进行编码的最简单方法是什么?例如,我想允许用户通过他们选择的属性(使用LINQ)来订购一些搜索结果.他们将在UI中选择"order by"属性 - 当然是字符串值.有没有办法直接使用该字符串作为linq查询的属性,而不必使用条件逻辑(if/else,switch)将字符串映射到属性.反射?
从逻辑上讲,这就是我想做的事情:
query = query.OrderBy(x => x."ProductId");
Run Code Online (Sandbox Code Playgroud)
更新:我最初没有指定我正在使用Linq to Entities - 看起来反射(至少GetProperty,GetValue方法)不会转换为L2E.
我有一个表,我想为每列做排序功能.
排序有两个方向asc和desc.
1)如何使用反射对列进行排序?
List<Person> GetSortedList(List<Person> persons, string direction, string column)
{
return persons.OrderBy(x => GetProperyByName(x, column)); //GetPropertyByName - ??
}
Run Code Online (Sandbox Code Playgroud)
2)我也想做一些我称之为linq运算符链的东西:
List<Person> GetSortedList(List<Person> persons, string direction, string column)
{
var linqChain;
if(direction=="up")
{
linqChain+=persons.OrderBy(x => GetProperyByName(x, column))
}
else
{
linqChain+=persons.OrderByDescending(x => GetProperyByName(x, column))
}
linqChain+=.Where(....);
return linqChain.Execute();
}
Run Code Online (Sandbox Code Playgroud)