2013-10-05 36 views
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小時。

但是,現在我需要得到每個組都有MaxVotesPostId。我怎麼做?

回答

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 ,你可以更容易地獲得。

+0

我看我在哪裏弄亂了我的問題。對不起。我需要每個組都有'Max'' Votes'的帖子。 –

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

我看到了我的問題。對不起。我需要每個組的最大投票數。 –

+0

編輯以獲得最佳投票的帖子。我想你可以有聯繫。 –