[英]Sorting one table result by highest count of items from another table
我有一個用於存儲我的產品的產品表,以及另一個獲得該產品用戶投票的表投票。
Product:
ID
Name
Price
etc..
Votes:
ID
ProductID
IpAdress
DateTimeCreated
在最近的24小時內,如何在linq to sql中獲得投票最多的產品? 我自己對L2S真的不滿意。
這是我到目前為止獲得的最接近的代碼,該代碼段應該獲得最后10票的投票權,但是我需要在過去24小時內獲得最高票數的投票權:
var last10Voted = (from vote in context.Votes join product in
context.Products on vote.ProductID equals
product.ID orderby vote.DateTimeCreated select product).Take(10);
var last10Voted =
(
from product in context.Products
let votes = context.Votes
.Where(v=>v.ProductID == product.ID
&& v.DateTimeCreated >= DateTime.Now.AddHours(-24))
orderby votes.Count() descending
select product
).Take(10);
var topVotedProducts =
Votes.Where(v => v.DateTimeCreated > DateTime.Now.AddHours(-24))
.GroupBy(v => v.ProductID)
.Join(Products, g => g.Key, p => p.ID, (g,p) => new { cnt = g.Count(), prod = p.Name })
.OrderByDescending(result => result.cnt);
產品:ID名稱價格等
投票:ID產品ID IpAdress DateTimeCreated
var mostVoted =
from product in context.Products
let votes = context.Votes.Count(vote => vote.ProductID == product.ID && (DateTime.Now - vote.DateTimeCreated).TotalHours <= 24)
orderby votes descending
select product;
var top10 = mostVoted.Take(10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.