如何获得每组的最大值?

时间:2021-07-20 12:49:50

Consider the following LINQ statement:

请考虑以下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);

It successfully groups a listing of posts into their respective groups: 24 hours, 168 hours, and 720 hours.

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

However, now I need to get the PostId that has the Max Votes for each group. How do I do that?

但是,现在我需要获得具有每组最大投票权的PostId。我怎么做?

2 个解决方案

#1


2  

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

Or, for a bit more clarity (IMHO), and (I think) less speed:

或者,为了更清晰(恕我直言),和(我认为)更低的速度:

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

The former has the benefit that if you want the post, and not just the PostId, you have that available more easily.

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

#2


1  

I was looking at this but kind of slow. It's a little different syntax so I'll post it anyway

我看着这个,但有点慢。这是一个不同的语法,所以无论如何我会发布它

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();

#1


2  

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

Or, for a bit more clarity (IMHO), and (I think) less speed:

或者,为了更清晰(恕我直言),和(我认为)更低的速度:

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

The former has the benefit that if you want the post, and not just the PostId, you have that available more easily.

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

#2


1  

I was looking at this but kind of slow. It's a little different syntax so I'll post it anyway

我看着这个,但有点慢。这是一个不同的语法,所以无论如何我会发布它

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();