我是LINQ的新手,并尝试使用MVC和LINQ构建一个网站。我想展示视图最多的前5个产品。我有2个表,如下所示,我解释尽可能简单。
PRODUCT
-------
ID
NAME
PRODUCT_VIEWS_TABLE
-------
ID
PRODUCT_ID
每次查看产品时,我都会向PRODUCT_VIEWS_TABLE插入一个新行。如何为此编写LINQ查询?
(from c in db.PRODUCT select c).Take(5)
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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();