Reputation: 426
I want to use reflection to write this code better. I now have the IsSearchable
and IsEditable
functions, but can I refactor this code to get the part c.Searchable and c.Editable out?
I have 10 functions like this and only need one. The only different part is what bool property to check, c.Searchable
or c.Editable
.
bool searchable = conditions
.Select(c => c.Searchable)
.SingleOrDefault();
bool editable = conditions
.Select(c => c.Editable)
.SingleOrDefault();
Upvotes: 1
Views: 75
Reputation: 19601
Using reflection is overkill. Assuming you are checking to see if there are ANY conditions in the list that match Editable
or Searchable
, you should maybe just use the Any()
syntax...
You could use a method such as
public bool CheckCondition(IEnumerable<Condition> conditions, Func<Condition, bool> predicate)
{
return conditions.Any(predicate);
}
and use it like:
var isSet = CheckCondition(conditions, c => c.Editable);
But you aren't saving yourself much. You might as well just write the Any()
every time. For example,
var isEditable = conditions.Any(c => c.Editable);
Upvotes: 3