[英]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.