skip to Main Content

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


  1. Okay, here is a solution to the problem:

    private static List<string> GetAllStringValuesFromObject(object model)
    {
        var result = new List<string>();
    
        PropertyInfo[] properties = model.GetType().GetProperties();
    
        foreach (PropertyInfo modelProp in properties)
        {
            if (modelProp.PropertyType == typeof(string))
            {
                result.Add(modelProp.GetValue(model).ToString());
            }
            else if (modelProp.PropertyType.IsClass)
            {
                // Pass in the value of the class, not the property itself, then add the result to the list.
                result.AddRange(GetAllStringValuesFromObject(modelProp.GetValue(model)));
            }
        }
    
        return result;
    }
    

    In your original GetAllStringValuesFromObject() you had one key thing wrong. In the event that the modelProp 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 the result list so it would return nothing.

    Hope this helps clear up the issue!

    Login or Signup to reply.
  2. 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. 😉

    // Object Extensions
    public static class ObjectExtensions
    {
        public static List<string> GetStringValues(this object o)
        {
            var values = new List<string>(); // List of string property values
            var properties = o.GetType().GetProperties(); // Get all properties
            foreach (var property in properties) // Loop through properties
            {
                if (property.PropertyType == typeof(string)) // Check if property is string
                    values.Add(property.GetValue(o).ToString()); // Add value to values
                else if (property.PropertyType.GetProperties().Length > 0) // Check if property has properties
                {
                    var subValues = GetStringValues(property.GetValue(o)); // Recursion
                    values.AddRange(subValues); // Add sub values to values
                }
            }
            return values;
        }
    }
    
    
    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"
        }
    };
    
    // Now you can simple call the method GetStringValues
    // that is extended to all of your objects
    apple.GetStringValues();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search