动态属性名称 [英] dynamic property name
本文介绍了动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个带有动态属性名称的linq查询.因此,例如,如果属性名称为"test",则简单查询如下所示:
I'm trying to write a linq query that takes a dynamic property name. So for example, if the property name is 'test', a simple query would look like this:
var test = testList.Select(x => x.test).Distinct().ToList();
但是我想动态生成属性名称,例如:
But I want to dynamically generate the property name, eg:
var propertyName = "test";
var test = testList.Select(x => x.propertyName).Distinct().ToList();
我收到一个错误消息,因为'propertyName'不是实际属性.
I get an error because 'propertyName' isn't an actual property.
实现此目标的最佳方法是什么?
What would be the best way to achieve this?
推荐答案
您必须使用反射来做您想做的事情:
You'd have to use reflection to do what you're trying to do:
var test = testList
.Select(x => x.GetType().GetProperty(propertyName).GetValue(x))
.Distinct()
.ToList();
这篇关于动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文