5

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

Anelook
  • 1,277
  • 3
  • 17
  • 28

1 Answers1

12

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");
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 3
    No! Marc Gravell shouldn't be here! This is a question for Jon Skeet! – Cole Tobin Apr 25 '13 at 14:30
  • Thanks a lot! Simple and effective! – Anelook Apr 25 '13 at 15:23
  • I have another connected question - what if I have in my View a more complicated property, an instance of a class. So not just a simple property which is String or Boolean, but an object which inside itself has more properties. For example, this is how I declare simple checkbox for such "inside" attributes '@Html.CheckBoxFor(m => m.Config.All)'. Is it possible to created such lambda, which would reflect the property inside an object - "m => m.Config.All". – Anelook Apr 26 '13 at 06:50
  • @Anelook you mean like this? http://stackoverflow.com/questions/16208214/construct-lambdaexpression-for-nested-property-from-string/16208620#16208620 – Marc Gravell Apr 26 '13 at 06:53
  • @MarcGravell yes, very close! But can I somehow convert it to Expression.Lambda>? I successfully can get correct lambda, but cannot cast it to the type I need. – Anelook Apr 26 '13 at 07:19
  • Figured it out. Thanks a lot for the help!! – Anelook Apr 26 '13 at 08:25
  • 1
    @Anelook, you should post your solution. – ps2goat Mar 21 '14 at 22:08
  • Is there any type of issue using "x" if this methods was used multiple times to create an expression tree to execute? (IE multiple "x"s in the expression tree) – Erik Philips Sep 10 '19 at 23:42
  • 1
    @ErikPhilips parameter expressions don't even need to be named; I suspect it only uses the name for the `.ToString()` representation of the expression tree. Obviously if you use the same name for multiple expressions: expect the `ToString()` to be slightly confusing. – Marc Gravell Sep 11 '19 at 07:12