代码之家  ›  专栏  ›  技术社区  ›  Jon Galloway

最受欢迎的GroupBy和Linq to实体

  •  1
  • Jon Galloway  · 技术社区  · 15 年前

    我有一个带有包含产品的invoiceline表的标准存储模式。我想得到一份按销售额排列的前五名产品的清单。最干净的方法是什么?这不是最好的方法:

        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>();
        }
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   Matt Hamilton    15 年前

    我不能精确地测试这个,但是你能简单地对生成的“产品”属性分组吗?

    return (from i in storeDB.InvoiceLines
                       group i by i.Product into g
                       orderby g.Count() descending
                       select g.Key)
        .Take(count).ToList();
    
        2
  •  1
  •   Amy B    15 年前

    通过在设计器中添加产品和invoiceline之间的关系,Cleaner仍然可以创建product.invoiceline属性。

    List<Product> result = storeDB.Products
      .OrderByDescending(p => p.InvoiceLines.Count())
      .Take(count)
      .ToList();