Zeeshanef
Zeeshanef

Reputation: 709

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?

Upvotes: 2

Views: 5049

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503280

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

Upvotes: 8

Related Questions