Linq to SQL:获得十大最受欢迎的产品

时间:2009-09-07 00:30:38

标签: sql linq-to-sql select

我想抓住10个最有序的产品。我的表看起来与此类似:

产品
ProductID | ProductName

OrderedProduct
ProductID | OrderID

顺序
OrderID | DateOrdered

目前我有以下内容:

return (from product in db.Products
        from orderedProduct in db.OrderedProducts
        where orderedProduct.ProductID == product.ProductID
        select product).OrderByDescending(???).Distinct().Take(10);

我在上面的查询中已经注意到我不确定要放什么。如何按订购产品表中显示的产品数量进行排序?

1 个答案:

答案 0 :(得分:16)

return (from product in db.Products
        from orderedProduct in db.OrderedProducts
        where orderedProduct.ProductID == product.ProductID
        group orderedProduct by product into productGroups
        select new 
        {
              product = productGroups.Key, 
              numberOfOrders = productGroups.Count() 
        }
        ).OrderByDescending(x => x.numberOfOrders).Distinct().Take(10);

它会给你10个项目,每个项目包含product对象,numberOfOrders整数。

修改

由于这将作为方法的返回值,并且由于C#不允许返回匿名类型(但此功能在C#4.0中),因此将匿名类型转换为类。

创建要返回类型的类

public class ProductOrders
{
    public ProductOrders() {
    }

    public Product product { get; set; }
    public int numberOfOrders { get; set; }
}

并使用此查询返回该类的对象

 return (from product in db.Products
        from orderedProduct in db.OrderedProducts
        where orderedProduct.ProductID == product.ProductID
        group orderedProduct by product into productGroups
        select new ProductOrders
        {
              product = productGroups.Key, 
              numberOfOrders = productGroups.Count() 
        }
        ).OrderByDescending(x => x.numberOfOrders).Distinct().Take(10);

现在返回值的类型为 IEnumerable<ProductOrders>