简体   繁体   中英

C# iterate through class properties and add to list certain types

EDIT I am sorry, my question was not clear. I want to add to the list not only the property name but its value

I want to iterate through all the properties of a class and find all properties of a certain type and add them to a list. The code I use to iterate is:

List<CustomAttribute> attributes = new List<CustomAttribute>();
PropertyInfo[] properties = typeof(CustomClass).GetProperties();

foreach (PropertyInfo property in properties)
{
    if (property.PropertyType == typeof(CustomAttribute))
    {
        //here I want to add property to list
    }
}

Any ideas?

Thanks

public static List<PropertyInfo> PropertiesOfType<T>(this Type type) =>
    type.GetProperties().Where(p => p.PropertyType == typeof(T)).ToList();

And you'd use it as follows:

var properties = typeof(CustomClass).PropertiesOfType<CustomAttribute>();

If what you need are the values of the properties of type T in a given instance then you could do the following:

 public static List<T> PropertyValuesOfType<T>(this object o) =>
        o.GetType().GetProperties().Where(p => p.PropertyType == typeof(T)).Select(p => (T)p.GetValue(o)).ToList();

And you'd use it as:

CustomClass myInstance = ...
var porpertyValues = myInstance.GetPropertyValuesOfType<CustomAttribute>();

Note that this just gives you the idea, you need to evaluate if dealing with properties with no getters is needed.

And last but not least, if you need the values and the property names, then you can build up a List of tuples to store the information:

public static List<Tuple<string, T>> PropertiesOfType<T>(this object o) =>
        o.GetType().GetProperties().Where(p => p.PropertyType == typeof(T)).Select(p => new Tuple<string, T>(p.Name, (T)p.GetValue(o))).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM