我有一个标准的商店架构,其中包含一个包含Products的InvoiceLine表。我希望按销售额列出销售前5名的产品。最干净的方法是什么?这不是最好的方法:
private List<Product> GetTopProducts(int count)
{
var topProducts = from invoiceLine in storeDB.InvoiceLines
group invoiceLine by invoiceLine.ProductId into grouping
orderby grouping.Count() descending
select new
{
Products = from Product in storeDB.Products
where grouping.Key == Product.ProductId
select Product
};
return topProducts.AsEnumerable().Cast<Product>().Take(count).ToList<Product>();
}
答案 0 :(得分:1)
我无法准确测试这个,但您可以简单地对生成的“Product”属性进行分组吗?
return (from i in storeDB.InvoiceLines
group i by i.Product into g
orderby g.Count() descending
select g.Key)
.Take(count).ToList();
答案 1 :(得分:1)
Cleaner仍在设计器中添加Product和InvoiceLine之间的关系 - 创建Product.InvoiceLines属性。
List<Product> result = storeDB.Products
.OrderByDescending(p => p.InvoiceLines.Count())
.Take(count)
.ToList();