0

考虑以下 LINQ 语句:

var posts = db.Posts
    .Where(p => p.Votes.Count > 0 && p.User.Confirmed)
    .Select(p => new
    {
        PostId = p.PostId,
        Votes = p.Votes.Count(),
        Hours = EntityFunctions.DiffHours(DateTime.UtcNow, p.Timestamp)
    })
    .Select(p1 => new
    {
        PostId = p1.PostId,
        Votes = p1.Votes,
        Group = p1.Hours <= 24 ? 24 :
            p1.Hours <= 168 ? 168 :
            p1.Hours <= 720 ? 720 : 0
    })
    .Where(p2 => p2.Group != 0);

它成功地将帖子列表分组到各自的组中:24 小时、168 小时和 720 小时。

但是,现在我需要为每个组获取PostId那个。Max Votes我怎么做?

4

3 回答 3

2
var postIds = posts.OrderByDescending(x => x.PostId).GroupBy(x => x.Group)
                   .Select(x => x.First().PostId);

或者,为了更清楚(恕我直言)和(我认为)速度更慢:

var postIds = posts.GroupBy(x => x.Group).Select(g => g.Max(p => p.PostId));

前者的好处是,如果您想要帖子,而不仅仅是PostId,您可以更轻松地获得它。

于 2013-10-05T16:39:59.357 回答
1

我正在看这个,但有点慢。这是一个有点不同的语法,所以我还是会发布它

var groups = (from p in posts
              group p by p.Group into g
              select new 
                {
                   Id = g.Max(p => p.Id),
                   Group = g.Key
                }).ToList();


var bestPosts = (from p in posts
                join j in groups on new {p.Group, p.Votes} equals new {j.Group, j.Votes}
                select p).ToList();
于 2013-10-05T16:55:09.340 回答
1

根据“GroupByField”分组并选择最大值。

var query = from o in _context.Objects
            group o by o.GroupByField
            into group
            select new
            {
                 maxParameter = (from o in group orderby o.OrderByField select o).Last()
            }; 

然后为了选择原始(最大)对象

var largest = query.Select(q => q.maxParameter).ToList();
于 2018-08-21T11:29:57.007 回答