Share via


Get most frequent item in a List

Question

Friday, July 31, 2009 7:49 PM

Hey everyone,

I have a List<string> users variable populated with names of people using a specific file and their name is added everytime they use the file. What would be the best way to get out of the list the most frequent user of this file? Essentially what item in the list is in there most often? 

Also if there is a tie, take the user that is closest to the top of the list.

Thanks!

-Adam

All replies (11)

Friday, July 31, 2009 7:57 PM ✅Answered | 2 votes

I didn't test this, but I think it would work:

var groupsWithCounts = from s in myStrings
    group s by s into g
    select new { 
        Item = g.Key, 
        Count = g.Count()
    };

var groupsSorted = groupsWithCounts.OrderByDescending(g => g.Count);
string mostFrequest = groupsSorted.First().Item;

Reed Copsey, Jr. - http://reedcopsey.com


Monday, August 3, 2009 4:59 PM ✅Answered

Do what Reed suggested, then check the first few entries to see if there is a tie (first few cause it could be between more than two), then iterate through the list from the start until you find one of those names.


Friday, July 31, 2009 8:32 PM

That worked wonderfully, Thanks!


Monday, August 3, 2009 3:45 PM

I am reopening this thread because the code that was given helps me with the first part, but I need it to also handle a tie between two users.

From above:

"Also if there is a tie, take the user that is closest to the top of the list."


Monday, August 3, 2009 5:36 PM

Unfortunately, the ordering will cause issues with ties.

Luckily, checking for ties is very easy with the code I pasted - if you look at groupsSorted, it has both the Item and the Count - so just check the first two elements, and if the Count is the same, you know you have a tie.

Unfortunately, as ScottyDoesKnow mentioend, in the case of a tie, you'll have to reiterate the original list until you find one of the elements to determine which came first, but that should be fairly easy.
Reed Copsey, Jr. - http://reedcopsey.com


Monday, August 3, 2009 5:45 PM

A small thing, don't just check the first two, you should keep checking until the count isn't the same (think of the case where there are 10 names all in the list once).


Monday, August 3, 2009 5:49 PM

How would I look at the first few items? I am sorry but I am not that familiar with Linq.


Monday, August 3, 2009 6:12 PM

Think you can just use indexes [] in a simple for loop.


Monday, August 3, 2009 6:29 PM

Ah thats stupid of me not to think of it as just any other variable. Thanks!


Monday, August 3, 2009 6:38 PM

Actually it returns an IEnumerable, or in this case an IOrderedEnumerable, which means you can't use indexers. You can use a foreach loop though.


Monday, August 3, 2009 6:45 PM

Wait I cant do that with groupsSorted. That is whats holding the data.