I have a standard store schema with an InvoiceLine table that contains Products. I'd like to get a list of the top 5 products by sales as a List. What's the cleanest way to do that? This can't be the best way:
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.Product开发者_运维知识库Id
select Product
};
return topProducts.AsEnumerable().Cast<Product>().Take(count).ToList<Product>();
}
I can't exactly test this, but can you simply group on the generated "Product" property?
return (from i in storeDB.InvoiceLines
group i by i.Product into g
orderby g.Count() descending
select g.Key)
.Take(count).ToList();
Cleaner still by adding a relationship between Product and InvoiceLine in the designer - creates Product.InvoiceLines property.
List<Product> result = storeDB.Products
.OrderByDescending(p => p.InvoiceLines.Count())
.Take(count)
.ToList();
精彩评论