Linq SubSelect with Expression Trees

时间:2015-09-11 13:45:20

标签: c# linq expression-trees

我有一个带有SubSelect的Linq声明:

query1 = from d in drivers 
         where d.Klasse == 3 && cars.Where(c => c.Driver == d.Name && c.Power == 120).Count() > 0 
         select d;

这很好用。现在我想对表达式树做同样的事情。

这就是我到目前为止所得到的。

ParameterExpression peCar = Expression.Parameter(typeof(Car), "c");
ParameterExpression peDriver = Expression.Parameter(typeof(Driver), "d");
Expression eKlasse = Expression.Property(peDriver, "Klasse");
Expression ePower = Expression.Property(peCar, "Power");
Expression eDriver = Expression.Property(peCar, "Driver");
Expression eName = Expression.Property(peDriver, "Name");

Expression eEx1 = Expression.Equal(eKlasse, Expression.Constant(3, typeof(int)));
Expression eEx2 = Expression.Equal(eDriver, eName);
Expression eEx3 = Expression.Equal(ePower, Expression.Constant(120, typeof(int)));
Expression eEx4 = Expression.And(eEx2, eEx3);

Expression<Func<Car, bool>> whereConditionSub = Expression.Lambda<Func<Car, bool>>(eEx4, new ParameterExpression[] { peCar });

Expression eSub1 = (Expression)cars.AsQueryable<Car>().Where(whereConditionSub).Count();
Expression eSub2 = Expression.GreaterThan(eSub1, Expression.Constant(0, typeof(int)));
Expression eEx5 = Expression.And(eEx1, eSub2);

Expression<Func<Driver, bool>> whereCondition = Expression.Lambda<Func<Driver, bool>>(eEx5, new ParameterExpression[] { peDriver });

query1 = drivers.AsQueryable<Driver>().Where(whereCondition);

但我仍然坚持如何将Sub-Query作为表达式引入主查询。

Expression eSub1 = (Expression)cars.AsQueryable<Car>().Where(whereConditionSub).Count();

知道怎么做吗?这有可能吗?

1 个答案:

答案 0 :(得分:1)

哇,这似乎是很多不可读的代码。我不确定你为什么要这样的东西,但无论如何...... 你不能将一个int转换为一个表达式,它不会工作。 Count为您提供结果,因此它执行表达式。您需要先捕获表达式,并将计数作为方法调用添加到顶部。 类似的东西:

if