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));
}
}
}
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" .
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.
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.
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);
}
}
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With