在C#中将对象的所有属性值获取到数组中:

huangapple go评论83阅读模式
英文:

Getting all values of properties of an object into an array in c#

问题

I'm 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, let's 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 is all the values of all properties of the class "Apple".

I tried this, and it didn't 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-minded way to do this? And can anyone help out? Thanks

英文:

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 = &quot;hodor&quot;, ReleasedYear = &quot;1999&quot;,
        SweetnessType = &quot;FruitLevel&quot;,
        Color = &quot;Green&quot;,
        StemType = new Stem()
        {
            name = &quot;stemar&quot;,
            supplier = &quot;apple&quot;
        }
    };

    // i want to get a result of [&quot;hodor&quot;, &quot;1999&quot;, &quot;fruitLevel&quot;, &quot;green&quot;, &quot;stemar&quot;, &quot;apple&quot;]

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&lt;string&gt; GetAllStringValuesFromObject(object model)
    {
        var result = new List&lt;string&gt;();

        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

答案1

得分: 1

以下是您要翻译的内容:

让我们创建一个扩展类来扩展您的对象类型。然后,我们可以在任何对象类中使用此扩展,例如苹果、香蕉和橙子。 在C#中将对象的所有属性值获取到数组中:

// Object Extensions
public static class ObjectExtensions
{
    public static List<string> GetStringValues(this object o)
    {
        var values = new List<string>(); // 字符串属性值列表
        var properties = o.GetType().GetProperties(); // 获取所有属性
        foreach (var property in properties) // 遍历属性
        {
            if (property.PropertyType == typeof(string)) // 检查属性是否为字符串
                values.Add(property.GetValue(o).ToString()); // 将值添加到列表
            else if (property.PropertyType.GetProperties().Length > 0) // 检查属性是否具有属性
            {
                var subValues = GetStringValues(property.GetValue(o)); // 递归
                values.AddRange(subValues); // 将子值添加到列表
            }
        }
        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"
    }
};

// 现在您可以简单地调用已扩展到所有对象的方法 'GetStringValues'
apple.GetStringValues();
英文:

Let´s create an Extension class to extend your object types. Then, we can use this extension below in any object class, such as apples, bananas, and oranges. 在C#中将对象的所有属性值获取到数组中:

// Object Extensions
public static class ObjectExtensions
{
    public static List&lt;string&gt; GetStringValues(this object o)
    {
        var values = new List&lt;string&gt;(); // 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 &gt; 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 = &quot;hodor&quot;, ReleasedYear = &quot;1999&quot;,
    SweetnessType = &quot;FruitLevel&quot;,
    Color = &quot;Green&quot;,
    StemType = new Stem()
    {
        name = &quot;stemar&quot;,
        supplier = &quot;apple&quot;
    }
};

// Now you can simply call the method &#39;GetStringValues&#39;
// that has been extended to all of your objects.
apple.GetStringValues();

答案2

得分: 0

以下是要翻译的代码部分:

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;
}

在您原始的 GetAllStringValuesFromObject() 中,有一个关键错误。在迭代的过程中,如果 modelProp 是一个类,您传递了 PropertyInfo 对象而不是属性本身的 Value。此外,您将其设置为在那一点返回,而不是将其添加到 result 列表,因此它将不返回任何内容。

希望这有助于澄清问题!

英文:

Okay, here is a solution to the problem:

private static List&lt;string&gt; GetAllStringValuesFromObject(object model)
{
    var result = new List&lt;string&gt;();

    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!

huangapple
  • 本文由 发表于 2023年6月1日 04:02:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定