一个聪明的家伙可以帮我写一个LINQ查询来获得最畅销的产品,我在Entity Framework模型中有这两个表/类:
Orders (OrderedItems)
OrderedItem (Product, Qty)
例如。 (这显然不起作用)
Orders.OrderByDescending(o => Sum(o.OrderedItems.Qty))
.Select(o => o.OrderedItems.Product)
答案 0 :(得分:4)
根本不需要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
答案 1 :(得分: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);
答案 2 :(得分:1)
我认为你错误地使用了Sum。我想这就是你想要的
Orders.OrderByDescending(o => o.OrderedItems.Sum(oi => oi.Qty))
.Select(o => o.OrderedItems.Product)
答案 3 :(得分: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;
}