dimanche 20 mai 2018

Using reflection to obtain list of DisplayNames from Class properties

I'm trying to obtain a List of DisplayNames out of a class that has most of its properties booleans:

public class AccessoriesModel
{
    public int Id { get; set; }

    [Display(Name = "Acc 1")]
    public bool Accessory1 { get; set; }

    [Display(Name = "Acc 2")]
    public bool Accessory2 { get; set; }

    [Display(Name = "Acc 3")]
    public bool Accessory3 { get; set; }

    [Display(Name = "Acc 4")]
    public bool Accessory4 { get; set; }
}

by iterating over the PropertyInfos of the class and seeing which values are true, as below:

    List<string> list = new List<string>();
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
        {
            if (propertyInfo.PropertyType == typeof(bool))
            {
                bool value = (bool)propertyInfo.GetValue(data, null);

                if (value)
                {
                   //add the DisplayName of the item who's value is true to the list named "list"

                   //the following line works fine, but I cannot iterate over the list of items to get dinamicaly build the list
                   string displayName = GetPropertyDisplayName<AccessoriesModel>(i => i.AirConditioning);

                   list.add(displayName)

                }
            }
        }

where GetPropertyDisplayName is a solution suggested by a fellow member in his answer for another question for retrieving the DisplayName of a property: https://stackoverflow.com/a/10048758

The end result that I'm looking for is a list of strings (display names) that will be formed only by the properties that are true.

Thank you, in advance, for your help on this.





Aucun commentaire:

Enregistrer un commentaire