4

聪明人可以帮我写一个 LINQ 查询来获得最畅销的产品,我在实体框架模型中有这两个表/类:

Orders (OrderedItems)
OrderedItem (Product, Qty)

例如。(这显然行不通)

Orders.OrderByDescending(o => Sum(o.OrderedItems.Qty))
      .Select(o => o.OrderedItems.Product)
4

4 回答 4

7

您根本不需要 Orders 表。假设每个订购的商品都有相应的订单,您应该能够做到这一点。

var query =
    (from item in OrderedItem
    group item.Qty by item.Product into g
    orderby g.Sum() descending
    select g.Key).Take(5); // get the top 5 orders
于 2012-11-02T04:41:50.393 回答
3
class Product {
            public int Id { get; set; }
        }
        class OrderedItem
        {
            public Product Product { get; set; }

            public int Qty { get; set; }
        }

进而:

        List<OrderedItem> orders = new List<OrderedItem>();
        var products = orders.GroupBy(p => p.Product.Id).OrderByDescending(pi => pi.Sum(pii => pii.Qty)).Select(p=>p.Key);
于 2012-11-02T04:41:32.330 回答
2

我认为您使用Sum不正确。我想这就是你想要的

Orders.OrderByDescending(o => o.OrderedItems.Sum(oi => oi.Qty))
      .Select(o => o.OrderedItems.Product)
于 2012-11-02T04:39:47.340 回答
0
    public IQueryable<Product> Bestsellers(int? count)
    {
        var query = (from item in db.OrderDetails
                     group item.Qty by item.Product into g
                     orderby g.Sum() descending
                     select g.Key).Take(count??20); // get the top 5 orders

        return query;
    }
于 2019-09-09T11:10:08.047 回答