Linq子选择表达式树

本文关键字:表达式 选择 Linq | 更新日期: 2023-09-27 18:12:15

我有一个Linq语句与SubSelect:

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();

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

Linq子选择表达式树

哇,这似乎是一大堆不可读的代码。我不知道你为什么想要这样的东西,但无论如何……你不能将int类型强制转换为表达式,这是行不通的。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);