如何获得每组的最大值?

时间:2013-10-05 16:32:50

标签: c# .net linq

考虑以下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的{​​{1}}。我该怎么做?

3 个答案:

答案 0 :(得分: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,那么您可以更轻松地获得该帖子。

答案 1 :(得分: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();

答案 2 :(得分: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();