简体   繁体   中英

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. Object can be any generic list like List<Country> , List<Area> or List<Region> but I need to get data by given 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?

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 ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM