views:

37

answers:

1

I did a fair bit of searching for an answer to this question, but no example that I could find got all the way to where I need to be.

I've got a Dictionary(Of SomeEnum, Integer) that gets filled up while looping through some objects that have a property with type SomeEnum. Once the loop is done, I want the SomeEnum type that occurs the most in the list of objects. I also need the other counts as well for display purposes, hence the usage of a simple Dictionary(Of K, V).

I am looking for a LINQ query to give me back the SomeEnum key that occurs the most by looking at each keys number of occurences. Or perhaps there's an easier way of going about it.

I could do this:

    Return (From kvp As KeyValuePair(Of SomeEnum, Integer) _
            In Me.MyObjects Order By kvp.Value Descending _
            Select kvp).First().Key

But wouldn't the sorting be a more expensive operation than trying to wiggle Max() in there somehow? I'm a LINQ n00b, so any feedback would be greatly appreciated.

+3  A: 

You can use the MaxBy method in MoreLINQ. There's a similar question already on StackOverflow (it's in C#, though). You can use it like:

Return dic.MaxBy(Function(pair) pair.Value).Key
Mehrdad Afshari