Fun (?) with Linq Expressions in extension methods

If you don’t need the title attribute on individual options your code could be simplified to: public static HtmlString SelectFor<TModel, TProperty, TIdProperty, TDisplayProperty, TListItem>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<TListItem> enumeratedItems, Expression<Func<TListItem, TIdProperty>> idProperty, Expression<Func<TListItem, TDisplayProperty>> displayProperty, object htmlAttributes ) where TModel : class { var id = (idProperty.Body as MemberExpression).Member.Name; var display = … Read more

How do I compose Linq Expressions? ie Func

While dtb’s answer works for several scenarios, it is suboptimal as such an expression cannot be used in Entity Framework, as it cannot handle Invoke calls. Unfortunately, to avoid those calls one needs a lot more code, including a new ExpressionVisitor derived class: static Expression<Func<A, C>> Compose<A, B, C>(Expression<Func<B, C>> f, Expression<Func<A, B>> g) { … Read more

How do I dynamically create an Expression predicate from Expression?

It’s hard to mix compiler-generated expression trees and hand-made ones, precisely because of this sort of thing – extracting out the ParameterExpressions is tricky. So let’s start from scratch: ParameterExpression argParam = Expression.Parameter(typeof(Service), “s”); Expression nameProperty = Expression.Property(argParam, “Name”); Expression namespaceProperty = Expression.Property(argParam, “Namespace”); var val1 = Expression.Constant(“Modules”); var val2 = Expression.Constant(“Namespace”); Expression e1 = … Read more

Convert Linq expression “obj => obj.Prop” into “parent => parent.obj.Prop”

What you’re looking for is the ability to compose expressions, just as you can compose functions: public static Expression<Func<T, TResult>> Compose<T, TIntermediate, TResult>( this Expression<Func<T, TIntermediate>> first, Expression<Func<TIntermediate, TResult>> second) { return Expression.Lambda<Func<T, TResult>>( second.Body.Replace(second.Parameters[0], first.Body), first.Parameters[0]); } This relies on the following method to replace all instances of one expression with another: public class … Read more