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

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.

于 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 に答える