Linq subquery same table using lambda

2019-09-04 03:56发布

问题:

I've been for a while trying to do using Linq and lambda expressions a query that I did already in SQL, but there is something that I'm missing...

This is the SQL query:

select o.ord_no from orders o  where 1 <= 
(select count(*) from orders where orders.purch_amt < o.purch_amt 
and orders.ord_date = '2012-02-14')

How could I do the same query but using Linq and lambda expressions???

回答1:

try this:

var date = DateTime.ParseExact("20120214", 
                              "yyyyMMdd", 
                               CultureInfo.InvariantCulture);    

var result = dbContext.orders
        .Where(q => dbContext.orders
                     .Where(s => s.purch_amt < q.purch_amt)
                     .Where(s => s.ord_date == date).Count() > 0)
        .ToList()