将2个参数Lambda表达式转换为1个参数Lambda表达式(指定一个参数)

我有表达

Expression<Func> CanBeDrivenBy = (car, driver) => car.Category == 'B' && driver.Age > 18; 

我想得到一些可以由一些司机驾驶的汽车

 IQueryable cars = ...; Driver driver = ...; cars.Where(CanBeDrivenBy); // Fail, expecting Expression<Func> 

所以我需要将Expression<Func>Expression<Func> (指定驱动程序)

是的,我可以使用

 cars.Where(c => c.Category == 'B' && driver.Age > 18); 

但我需要能够动态改变表达式的解决方案。 我需要传递Expression(使用entity framework)

您可以重用源表达式体的修改版本

 using System; using System.Linq.Expressions; public class Program { public static Expression> Bind2nd(Expression> source, T2 argument) { Expression arg2 = Expression.Constant(argument, typeof (T2)); Expression newBody = new Rewriter(source.Parameters[1], arg2).Visit(source.Body); return Expression.Lambda>(newBody, source.Parameters[0]); } public static void Main(string[] args) { Expression> f = (a, b) => a.Length + b.Length; Console.WriteLine(f); // (a, b) => (a.Length + b.Length) Console.WriteLine(Bind2nd(f, "1")); // a => (a.Length + "1".Length) } #region Nested type: Rewriter private class Rewriter : ExpressionVisitor { private readonly Expression candidate_; private readonly Expression replacement_; public Rewriter(Expression candidate, Expression replacement) { candidate_ = candidate; replacement_ = replacement; } public override Expression Visit(Expression node) { return node == candidate_ ? replacement_ : base.Visit(node); } } #endregion } 

这个工作

我写了这个函数,通过指定第二个参数来减少从2到1的参数数量。

 public static Expression> Bind2nd(Expression> source, T2 argument) { Expression arg2 = Expression.Constant(argument, typeof(T2)); var arg1 = Expression.Parameter(typeof(T1)); return Expression.Lambda>(Expression.Invoke(source, arg1, arg2), arg1); } 

用法:

 IQueryable cars = ...; Driver driver = ...; cars.Where(Bind2nd(CanBeDrivenBy, driver)); 

arg1是调用之间的临时存储。

有任何系统等效function吗?