2015-03-02 69 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();