我正在尝试编写一个带有动态属性名称的linq查询.因此,例如,如果属性名称为"test",则简单查询将如下所示:
var test = testList.Select(x => x.test).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
但我想动态生成属性名称,例如:
var propertyName = "test";
var test = testList.Select(x => x.propertyName).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
我收到错误,因为'propertyName'不是实际属性.
实现这一目标的最佳方法是什么?
its*_*e86 12
你必须使用反射来做你想做的事情:
var test = testList
.Select(x => x.GetType().GetProperty(propertyName).GetValue(x))
.Distinct()
.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2221 次 |
| 最近记录: |