简体   繁体   English

LINQ查询中的orderby Count(other_table)

[英]orderby Count(other_table) in linq query

As mentioned in the Title, I want to orderby the result table using column of another table. 如标题中所述,我想使用另一个表的列对结果表进行orderby

var products = (from p in db.Products
               join o in db.OrderDetails on p.ProductID equals o.ProductID
               orderby count(o.Quantity) <-- want to do something like this
               select p).Distinct().Take(8).ToList();

Below is the SQL Equivalent statement. 下面是SQL等效语句。

SELECT Products.ProductID FROM Products
INER JOIN OrderDetail on OrderDetail.ProductID = Products.ProductID
GROUP BY Products.ProductID
ORDER BY COUNT(OrderDetail.Quantity)

And I am getting desired results. 而且我正在获得理想的结果。 But how can I do it using LINQ? 但是如何使用LINQ做到这一点?

Just create a dictionary where the key is Product and value is calculated Quantity, and after that perform your query. 只需创建一个词典,键为产品,值为计算数量,然后执行查询。

Or do it like this way: 或这样做:

var product = p in resultOfTheJoin
        let count = resultOfTheJoin.Quantity.Count()
        orderby count
        select p;

If i understand, you need a just like that. 如果我明白的话,您就需要这样。 Pls try this: 请尝试一下:

       var query = (from p in db.Products
                     join o in db.OrderDetails on p.ProductID equals o.ProductID into orderTemp
                     select new type
                     {
                       Product_id = p.Product_id,
                       //set product attribtes,
                       OrderDetail_id = orderTemp.OrderDetail_id,
                       Quantity = orderTemp.Quantity,
                       // set OrderDetail attributtes

                     }.OrderBy(l => l.Quantity.Count()).ToList();

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

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