13

I have a class that has lots of bool properties. How can I create another property that is a list of strings that contains the name of the properties which have a value of true?

See initial attempt below - can't quite figure out how to filter the true ones

public class UserSettings
{
    public int ContactId { get; set; }
    public bool ShowNewLayout { get; set; }
    public bool HomeEnabled { get; set; }
    public bool AccountEnabled { get; set; }

    // lots more bool properties here

    public IEnumerable<string> Settings
    {
        get
        {
            return GetType()
                .GetProperties()
                .Where(o => (bool)o.GetValue(this, null) == true) //this line is obviously wrong
                .Select(o => nameof(o));
        }
    }
}
ChrisCa
  • 10,876
  • 22
  • 81
  • 118

2 Answers2

23

You can do it like this - all those properties that are of type bool and are true

public IEnumerable<string> Settings
{
    get
    {
        return GetType()
            .GetProperties().Where(p => p.PropertyType == typeof(bool) 
                                         && (bool)p.GetValue(this, null))
            .Select(p => p.Name);
    }
}
AlexB
  • 7,302
  • 12
  • 56
  • 74
Nino
  • 6,931
  • 2
  • 27
  • 42
5

Without LINQ:

foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
    if (propertyInfo.PropertyType == typeof(bool))
    {
        bool value = (bool)propertyInfo.GetValue(data, null);

        if(value)
        {
           //add propertyInfo to some result
        }
    }
}            
Adam Jachocki
  • 1,897
  • 1
  • 12
  • 28