Im trying to get all the field values of an object into an array. but the problem is the fields of the object can have other types rather than string but ultimately all the values should be a string.
So for example lets say we have a class of red
public class Apple
{
public string Name { get; set; }
public string ReleasedYear { get; set; }
public string SweetnessType { get; set; }
public string Color { get; set; }
public Stem StemType { get; set; }
}
public class Stem
{
public string name { get; set; }
public string supplier { get; set; }
}
var apple = new Apple()
{
Name = "hodor", ReleasedYear = "1999",
SweetnessType = "FruitLevel",
Color = "Green",
StemType = new Stem()
{
name = "stemar",
supplier = "apple"
}
};
// i want to get a result of ["hodor", "1999", "fruitLevel", "green", "stemar", "apple"]
as seen above the result i want to get are all the values of all properties of the class "Apple".
i tried this and it didnt work
private List<string> GetAllStringValuesFromObject(object model)
{
var result = new List<string>();
PropertyInfo[] properties = model.GetType().GetProperties();
foreach (PropertyInfo modelProp in properties)
{
if (modelProp.PropertyType.IsClass)
{
return GetAllStringValuesFromObject(modelProp);
}
if (modelProp.PropertyType == typeof(string))
{
result.Add(modelProp.GetValue(model).ToString());
}
}
return result;
}
is there a performance mindful way to do this? and can anyone help out? Thanks
2
Answers
Okay, here is a solution to the problem:
In your original
GetAllStringValuesFromObject()
you had one key thing wrong. In the event that themodelProp
being iterated over was a class, you passed in the PropertyInfo object instead of the property’s Value. Additionally, you had it setup to return at that point instead of adding to theresult
list so it would return nothing.Hope this helps clear up the issue!
Consider creating an Extension class to extend your object types. Then, you can use this extension below in any object class, such as apples, bananas, and oranges. 😉