我有表情
Expression<Func<Car, Driver, bool>> CanBeDrivenBy =
(car, driver) => car.Category == 'B' && driver.Age > 18;
我想要一些可以由司机驾驶的汽车
IQueryable<Cars> cars = ...;
Driver driver = ...;
cars.Where(CanBeDrivenBy); // Fail, expecting Expression<Func<Car, bool>>
所以我需要转换Expression<Func<Car, Driver, bool>>
to Expression<Func<Car, bool>>
(指定驱动程序)
是的,我可以使用
cars.Where(c => c.Category == 'B' && driver.Age > 18);
但我需要具有可以动态更改的表达式的解决方案。我需要传递表达式(使用实体框架)
您可以重用源表达式主体的修改版本
using System;
using System.Linq.Expressions;
public class Program
{
public static Expression<Func<T1, TResult>> Bind2nd<T1, T2, TResult>(Expression<Func<T1, T2, TResult>> source, T2 argument)
{
Expression arg2 = Expression.Constant(argument, typeof (T2));
Expression newBody = new Rewriter(source.Parameters[1], arg2).Visit(source.Body);
return Expression.Lambda<Func<T1, TResult>>(newBody, source.Parameters[0]);
}
public static void Main(string[] args)
{
Expression<Func<string, string, int>> 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)