使用Linq获取Top x产品

Cla*_*reG 0 c# linq linq-to-entities linq-query-syntax

我需要使用Linq to Entities获得前10名记录.

我需要将返回的结果绑定到GridView如下"

Product Name  |   Product Description  |   Number of Items Sold

Item 1        |   Item 1 Description   |           24
Run Code Online (Sandbox Code Playgroud)

如上所述,物品需要按顺序存储,从销售的大多数商品开始.

我试了几个例子,比如这个,这个,跟着例子在这里.

以下是我到目前为止所尝试的内容:

public IQueryable GetTopTenProducts(DateTime startDate, DateTime endDate)
{
    return
        (from p in this.Entities.Product
         join pro in this.Entities.ProductOrder on p.ID equals pro.ProductID
         join o in this.Entities.Order on pro.OrderID equals o.ID
         where o.DateOfOrder >= startDate && o.DateOfOrder <= endDate
         select new
         {
             Product = p,
             Quantity = pro.Qty,
             ProductName = p.Name,
             ProductDescription = p.Description

         } into productQty
         group productQty by productQty.Product into pg
         let totalQuantity = pg.Sum(prod => prod.Quantity)
         orderby totalQuantity descending
         select pg.Key).Take(10);
}
Run Code Online (Sandbox Code Playgroud)

这将返回整个产品表,但我只需要检索上面粘贴的详细信息.

有任何想法吗?

Mic*_*haC 5

我想你必须改变你的最后一个选择select pg.Key来选择你想要的

例如: select new { pg.Key.ProductName, pg.Key.ProductDescription, totalQuantity }