[英]Cast Object into Generic List to get List of Items
Is there any way that I can cast unknown object into generic list to get list of items from object by given ProperyName. 是否有任何方法可以将未知对象转换为通用列表,以通过给定的ProperyName从对象获取项目列表。 Object can be any generic list like
List<Country>
, List<Area>
or List<Region>
but I need to get data by given displayMember
. 对象可以是任何通用列表,如
List<Country>
, List<Area>
或List<Region>
但我需要通过给定的displayMember
获取数据。
For Example: 例如:
List<City> listCities = new List<City>(); //Cities data with (CityID, CityName)
object dataSource = listCities;
string displayMember = "CityName";
string valueMember = "CityID";
How to get List of CityName
from dataSource
object of object type? 如何从对象类型的
dataSource
对象获取CityName
列表?
You'd have to use reflection, basically. 基本上你必须使用反射。 For example:
例如:
// This assumes it really is just a List<T>...
IEnumerable list = (IEnumerable) dataSource;
Type elementType = list.GetType().GetGenericArguments()[0];
PropertyInfo property = elementType.GetProperty(displayMember);
List<object> displayValues = list.Cast<object>()
.Select(v => property.GetValue(v, null))
.ToList();
(You'd want to add a bunch of error checking - for example, that property
isn't null
...) (你想添加一堆错误检查 - 例如,该
property
不为null
...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.