Reputation: 57
I am working on a project who need to list and store some model's content and add it in list.
Here is my model :
public class ProductPage
{
public string Name { get; set; }
public string Reference { get; set; }
public string Color { get; set; }
}
And here is my code :
public List<TechnicalAttributes> GetAttributeFromProduct(ProductPage product)
{
List<TechnicalAttributes> attributeList = new List<TechnicalAttributes>();
foreach (PropertyInfo pi in product.GetType().GetProperties())
{
if (pi.PropertyType == typeof(string))
{
string value = (string)pi.GetValue(product);
if (!string.IsNullOrEmpty(value))
{
if (!Helper.IsNumeric(value))
{
attributeList.Add(new TechnicalAttributes() { Name = GetVariableName(() => value), Value = value });
}
}
}
}
return attributeList;
}
My code allow me to get this :
type = "value" - attribute = "myName"
type = "value" - attribute = "myReference"
type = "value" - attribute = "myColor"
but I want to have something like this :
type = "Name" - attribute = "myName"
type = "Reference" - attribute = "myReference"
type = "Color" - attribute = "myColor"
I need to use a foreach because I have way more parameters in my model ! Can someone help me please ?
Upvotes: 1
Views: 717
Reputation: 57
Problem solved,
You can have the parameters name with the property Info.
pi.Name;
Upvotes: -1
Reputation: 6716
I guess you want to use pi.Name
to get the name of the property.
This property is part of System.Reflection.MemberInfo
and is available in PropertyInfo
as well. It will give you the name of the property.
Upvotes: 2