简体   繁体   English

带有表达式树的 Linq SubSelect

[英]Linq SubSelect with Expression Trees

I have a Linq Statement with a 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;

This works fine.这工作正常。 Now I want to do the same with expression trees.现在我想对表达式树做同样的事情。

This is, what I've got so far.这是,我到目前为止所得到的。

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

But I'm stuck on how to get the Sub-Query as an Expression into the main query.但我坚持如何将子查询作为表达式添加到主查询中。

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

Any idea how to do this?知道如何做到这一点吗? Is this possible at all?这可能吗?

Wow, that seems like a lot of not readable code.哇,这似乎是很多不可读的代码。 Im unsure why you would like to have something like this, but anyways... You cannot cast an int to an Expression, it wont work.我不确定你为什么想要这样的东西,但无论如何......你不能将 int 转换为表达式,它不会工作。 Count delivers you the result, so it executes the expression. Count 为您提供结果,因此它执行表达式。 You need to catch the expression before, and add the count as a method call on top.您需要先捕获表达式,并将计数添加为顶部的方法调用。 Something like:就像是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM