聪明人可以帮我写一个 LINQ 查询来获得最畅销的产品,我在实体框架模型中有这两个表/类:
Orders (OrderedItems)
OrderedItem (Product, Qty)
例如。(这显然行不通)
Orders.OrderByDescending(o => Sum(o.OrderedItems.Qty))
.Select(o => o.OrderedItems.Product)
聪明人可以帮我写一个 LINQ 查询来获得最畅销的产品,我在实体框架模型中有这两个表/类:
Orders (OrderedItems)
OrderedItem (Product, Qty)
例如。(这显然行不通)
Orders.OrderByDescending(o => Sum(o.OrderedItems.Qty))
.Select(o => o.OrderedItems.Product)
您根本不需要 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
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);
我认为您使用Sum不正确。我想这就是你想要的
Orders.OrderByDescending(o => o.OrderedItems.Sum(oi => oi.Qty))
.Select(o => o.OrderedItems.Product)
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;
}