Reputation: 419
I had a list as ProductSpec {id, Name}
and another list as Product {productspec, id, Name}
.
When I try access the properties of Product into
IList<PropertyInfo> properties = typeof(Product).GetProperties().ToList();
I am retreving my id and name as a property which is fine but when I try to reiterate a productspec as
foreach(var property in properties)
{
IList<PropertyInfo> properties = property.propertytype.getproperties();
// I am not getting the productspec columns
//instead I am getting (capacity,count ) as my properties..
}
So how do I reiterate a list from a list to get the list properties
Upvotes: 0
Views: 7122
Reputation: 236218
You need to use same code for property type:
var innerProperties = property.PropertyType.GetProperties().ToList();
Also rename result - it conflicts with variable in foreach
loop.
Upvotes: 3
Reputation: 2596
Is the type of the ProductSpec
in the Product
class of type ProductSpec
or of type List<ProductSpec>
? If it is a list you could do the following:
var properties = new List<PropertyInfo>();
foreach (var property in properties)
{
if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)
&& property.PropertyType.IsGenericType
&& property.PropertyType.GetGenericArguments().Length == 1)
{
IList<PropertyInfo> innerProperties = property.PropertyType.GetGenericArguments()[0].GetProperties();
//should contain properties of elements in lists
}
else
{
IList<PropertyInfo> innerProperties = property.PropertyType.GetProperties();
//should contain properties of elements not in a list
}
}
Upvotes: 3
Reputation: 717
Try this:
PropertyInfo[] propertyInfos = typeof(Product).GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var inner = propertyInfo.PropertyType.GetProperties().ToList();
}
public class Product
{
public ProductSpec Spec { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
public class ProductSpec
{
public string Id { get; set; }
public string Name { get; set; }
}
Upvotes: 0