Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the names of all the boolean properties of a class which are true

Tags:

c#

reflection

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));
        }
    }
}
like image 841
ChrisCa Avatar asked Apr 24 '17 13:04

ChrisCa


People also ask

How do you know if a boolean value is true?

If you need to be sure you have a boolean primitive value, and not just a falsy value, check the type of the JavaScript variable using typeof . Only true and false have a typeof equal to "boolean" .

Is a Boolean type property?

The Boolean property data type stores a true or false value. When a Boolean property value is set, a null value is treated as false and any other value is treated as true. The attributes for a Boolean property include the true and false value.

How do you check if a variable is boolean in Python?

We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.


2 Answers

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);
    }
}
like image 102
Nino Avatar answered Nov 04 '22 06:11

Nino


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
        }
    }
}            
like image 22
Adam Jachocki Avatar answered Nov 04 '22 06:11

Adam Jachocki