Linq to SQL:获取前 10 名最常订购的产品
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1387110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq to SQL: Get top 10 most ordered products
提问by ajbeaven
I'm wanting to grab the 10 most ordered products. My tables look similar to this:
我想获取 10 个最常订购的产品。我的表看起来类似于:
ProductProductID | ProductName
产品ProductID | ProductName
OrderedProductProductID | OrderID
订购产品ProductID | OrderID
OrderOrderID | DateOrdered
命令OrderID | DateOrdered
At the moment I've got the following:
目前我有以下几点:
return (from product in db.Products
from orderedProduct in db.OrderedProducts
where orderedProduct.ProductID == product.ProductID
select product).OrderByDescending(???).Distinct().Take(10);
I've noted in the above query where I'm uncertain of what to put. How do I orderby the number of products that appear in the ordered products table?
我在上面的查询中注意到我不确定要放什么。如何根据已订购产品表中出现的产品数量进行订购?
回答by Aziz
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);
It will give you 10 items, each item contains product object, and numberOfOrders integer.
它将为您提供 10 个项目,每个项目包含产品对象和 numberOfOrders 整数。
Edit:
编辑:
Since this will be as a return value for a method, and since C# doesn't allow returning an anonymous type (yet .. this feature is in C# 4.0), you convert the anonymous type into a class.
由于这将作为方法的返回值,并且 C# 不允许返回匿名类型(但 .. 此功能在 C# 4.0 中),因此您将匿名类型转换为类。
Create a class of the type you want to return
创建一个你想要返回的类型的类
public class ProductOrders
{
public ProductOrders() {
}
public Product product { get; set; }
public int numberOfOrders { get; set; }
}
and Use this query to return objects of that class
并使用此查询返回该类的对象
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);
The return value now is of type IEnumerable<ProductOrders>
.
现在返回值的类型是IEnumerable<ProductOrders>
。