tags:

views:

100

answers:

4

Hi,

i have a list of articles, and each article has one or more votes in a collection. It's a entity framework collection, but i don't think that makes a lot of difference for the problem. Navigating goes like this:

Article.Votes, where Votes is a collection of vote objects. What i'm looking for is the Linq statement how i can find the top 5 articles with most votes. So 1 articles has 100 votes (vote objects in the Votes collection), 3 have 90, 1 have 88, 4 have 78, etc, then i want to select the ones with 100, 90 and 88. The article collection, btw, is not sorted on the number of votes.

Regards, Michel

+1  A: 
var top5Articles = listOfArticles.OrderByDescending(a => a.Votes.Count).Take(5);

Not tested, but SHOULD work...

BFree
Needs to be order by descending...
Reed Copsey
Excellent point, that's what happens when you rush to be first. Fixed...
BFree
+4  A: 
var articles = GetArticleList();
var topArticles = articles.OrderByDescending(a => a.Votes.Count).Take(5);

You need the descending clause so you get the highest voted articles first.

Jake Pearson
+3  A: 
var top5 = (from a in articles
       orderby a.Votes.Count descending
       select a).Take(5);
Reed Copsey
A: 

How about

Articles.OrderByDescending(pArticle => pArticle.Votes.Max(pVote => pVote.Num))
        .Take(5)
Vasu Balakrishnan