Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Expression<Func<TModel, TProperty>>;

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).

like image 617
Anelook Avatar asked Apr 25 '13 14:04

Anelook


People also ask

What are expressions c#?

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.

What is expression in Linq?

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.


1 Answers

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");
like image 150
Marc Gravell Avatar answered Oct 15 '22 01:10

Marc Gravell