views:

36

answers:

2

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.ProductId
                            select Product
                        };
        return topProducts.AsEnumerable().Cast<Product>().Take(count).ToList<Product>();
    }
+1  A: 

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();
Matt Hamilton
Thanks. I always forget that you can group on generated properties rather than ID fields.
Jon Galloway
+1  A: 

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();
David B
Thanks, that's even better!
Jon Galloway