Is it possible to create Expression<Func<TModel, bool>>()
which can be used in different htmlHelpers (for instance in CheckBoxFor()
), if I have a model object
this HtmlHelper<TModel> htmlHelper
and name of the property (through reflection).
An expression in C# is a combination of operands (variables, literals, method calls) and operators that can be evaluated to a single value. To be precise, an expression must have at least one operand but may not have any operator.
In LINQ, a query expression is compiled to expression trees or to delegates, depending on the type that is applied to query result. The IEnumerable<T> type LINQ queries are compiled to delegates and IQueryable or IQueryable<T> queries are compiled to expression trees.
Sure:
static Expression<Func<TModel,TProperty>> CreateExpression<TModel,TProperty>(
string propertyName)
{
var param = Expression.Parameter(typeof(TModel), "x");
return Expression.Lambda<Func<TModel, TProperty>>(
Expression.PropertyOrField(param, propertyName), param);
}
then:
var lambda = CreateExpression<SomeModel, bool>("IsAlive");
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