带有表达式树的 Linq SubSelect

Linq SubSelect with 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);

但我一直在研究如何将子查询作为表达式放入主查询中。

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

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

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

var whereExp = cars.AsQueryable<Car>().Where(whereConditionSub).Expression;
var countMethod = new Func<IQueryable<Car>, int>(Queryable.Count).Method;
var eSub1 = Expression.Call(countMethod, whereExp);