Reputation: 21
Is this possible to do in C#
?
I have POCO object here is definition:
public class Human
{
public string Name{get;set;}
public int Age{get;set;}
public int Weight{get;set;}
}
I would like to map properties of object Human
to string array.
Something like this:
Human hObj = new Human{Name="Xi",Age=16,Weight=50};
Or I can have List<Human>
:
string [] props = new string [COUNT OF hObj PROPERTIES];
foreach(var prop in hObj PROPERTIES)
{
props["NAME OF PROPERTIES"] = hObj PROPERTIES VALUE
}
Upvotes: 1
Views: 9831
Reputation: 8008
It should be something like this:
var props = new Dictionary<string, object>();
foreach(var prop in hObj.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance);)
{
props.Add(prop.Name, prop.GetValue(hObj, null));
}
see here for info on GetProperties and here for PropertyInfo
Upvotes: 2
Reputation: 21
You can use reflection to get an object's properties and values:
var properties = typeof(Human).GetProperties();
IList<KeyValuePair<string, object>> propertyValues = new List<KeyValuePair<string, object>>();
foreach (var propertyInfo in properties)
{
propertyValues.Add(propertyInfo.Name, propertyInfo.GetValue(oneHuman));
}
Upvotes: 0