4

I am trying to create this lambda (x => x.MenuItemId) but I am not sure how to do that.

var item = Expression.Parameter(typeof(MenuItem), "x");
var prop = Expression.Property(item, "MenuItemId");
var lambda = Expression.Lambda<Func<MenuItem, object>>(x => x.MenuItemId);

2 Answers 2

9

You want to create the lambda with the item and prop you already declared

var lambda = Expression.Lambda<Func<MenuItem, object>>(prop, item);

You can also choose to strongly type the resulting lambda to the type of x.MenuItemId - if it is a string that would be like this:

var lambda = Expression.Lambda<Func<MenuItem, string>>(prop, item);

You would invoke the resulting lambda using Compile(), then using it where you would use a lambda otherwise.

For example, if you had a collection of MenuItem called items, and you wanted all the MenuItemId:

var compiled = lambda.Compiled(); 
var itemIds = items.Select(compiled); // roughly equivalent items.Select(x => x.MenuItemId);

I've written a little utility class (ugh, I know) to wrap this functionality:

static class Gen<TModel, TProp> {
    public static Func<TModel, TProp> SelectorExpr(string propertyName) {
        var pExpr = Expression.Parameter(typeof (TModel));
        var mExpr = Expression.Property(pExpr, propertyName);
        var lExpr = Expression.Lambda<Func<TModel, TProp>>(mExpr, pExpr);
        return lExpr.Compile();
    }
}

Use of above:

var results = items.Select(Gen<MenuItem, object>.SelectorExpr("MenuItemId"));
Sign up to request clarification or add additional context in comments.

Comments

7

Just a note: if you know how lambda expression will look like at design time (rather than having it computed based on variables at compile time), then the following code should make the expression tree you need:

Expression<Func<MenuItem, object>> lambda = x => x.MenuItemId;

No need to build expressions piece by piece if the pieces themselves are always the same. ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.