2015-03-02 85 views
2

我是LINQ的新手,并尝试使用MVC和LINQ构建网站。我想展示最具意见的前5名产品。我有如下两个表格,我正在尽可能简单地解释。如何获得最高观点的前5名产品?

PRODUCT 
------- 
ID 
NAME 

PRODUCT_VIEWS_TABLE 
------- 
ID 
PRODUCT_ID 

每次查看产品时,我都会向PRODUCT_VIEWS_TABLE插入新行。我怎样才能为此编写LINQ查询?

(from c in db.PRODUCT select c).Take(5) 

回答

1
var topProductsIds = db.PRODUCT_VIEWS_TABLE // table with a row for each view of a product 
    .GroupBy(x => x.PRODUCT_ID) //group all rows with same product id together 
    .OrderByDescending(g => g.Count()) // move products with highest views to the top 
    .Take(5) // take top 5 
    .Select(x => x.Key) // get id of products 
    .ToList(); // execute query and convert it to a list 

var topProducts = db.PRODUCTS // table with products information 
    .Where(x=> topProductsIds.Contains(x.ID)); // get info of products that their Ids are retrieved in previous query 
+0

。选择()和.OrderByDescending()行不编译。 – 2015-03-02 20:48:09

+0

错字,固定.... – dotctor 2015-03-02 20:49:07

+1

第一个。从顶部选择,并在..OrderByDescending下面。它说“无效的匿名....” – 2015-03-02 20:52:18

3

如何:

var top5 = productViews 
      .GroupBy(view => view.ProductId) // group views by product 
      .OrderByDescending(g => g.Count()) // order from most- to least-viewed 
      .Take(5)       // take the top 5 
      .Select(g => g.First().Product); // fetch the corresponding product 
+0

如果延迟加载被禁用,这将无法正常工作。 – dotctor 2015-03-02 20:55:51

+0

这个问题没有规定。 – 2015-03-02 20:57:43

+0

我刚才提到,更多信息,简单LINQ的+1 – dotctor 2015-03-02 20:58:58

1

试试这个:

var topProducts = m_context.PRODUCTS 
    .Join(m_context.PRODUCT_VIEW, product=> product.Id, view => view.ProductId, 
     (product, view) => new { ProductId = product.Id, ViewId = view.Id}) 
    .GroupBy(g => g.ProductId) 
    .Select(s => new { 
     Id = s.Key, 
     ViewCount= s.Count() 
    }) 
    .OrderByDescending(o => o.ViewCount) 
    .Take(5).ToList();