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"));