0

我有一个表 Products 用于存储我的产品,另一个表 Votes 包含用户对该产品的投票。

Product:
ID
Name
Price
etc..

Votes:
ID
ProductID
IpAdress
DateTimeCreated

我如何在 linq to sql 中获得过去 24 小时内投票最多的产品?我真的不太擅长 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);
4

3 回答 3

2
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);
于 2012-04-25T11:05:07.263 回答
1
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 ProductID IpAdress DateTimeCreated

于 2012-04-25T11:07:52.823 回答
0
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);
于 2012-04-25T11:08:58.507 回答