Find the key with the maximum value from SortedDictionary?

I have a SortedDictionary , how to find the key associated with the maximum value? Do I have to go through each KeyValuePair?

+4
source share
5 answers

If dict is your SortedDictionary<,> , and you want all keys to match the maximum value, first check that the dict not null or empty (you need at least one element). Then maybe it works:

 var max = dict.Values.Max(); var relevantKeys = dict.Where(pair => max.Equals(pair.Value)) .Select(pair => pair.Key); 

Maybe this can be done more efficient?

+4
source

Use Enumerable.OrderByDescending() , and then access the Key property of what First() returns like this:

  var dict = new SortedDictionary<string, string> { {"key1", "value3"}, {"key2", "value1"}, {"key3", "value2"}, }; var max = dict.OrderByDescending(d => d.Value).First(); var key = max.Key; 
+2
source

You can use the MaxBy method in MoreLinq to efficiently execute this query.

 var result = dictionary.MaxBy(pair => pair.Value).Key; 

This will only be necessary to reprocess the data once, and not to sort the values โ€‹โ€‹and get the first result (which will be O(n * log(n)) ).

Since only keys, not values, are sorted, there is no way to execute this query without missing at least one cycle after each key pair.

Another option is to have two SortedDictionaries. You already have one of them, and the other is a reverse dictionary. For each value in the current dictionary, you can add it as a key to the second dictionary, and the value of the second dictionary will be the key in the first (if it is a ratio from one to many, and not one to one, the value of the reverse search should be a list of elements). Although it will be programmatically โ€œexpensiveโ€ (more memory than in time, but still some of them) to create this second dictionary, as soon as you do this, you can efficiently query based on values, not keys.

+1
source

Getting the key associated with the maximum value means that you are not actually using the default SortedDictionary sort order. This is because SortedDictionar orders the key, not Value. So, to do what you want, you will do it in the old fashioned LINQ way:

 sortedDict.OrderByDescending(kvp => kvp.Value).First().Key 
0
source

In order to get all the keys that contain the maximum value that you are interested in, you need to do some data processing. This is actually quite convenient in C #.

This can be done by doing some combination of Linq

 // first of all, group your dictionary by the value you want to have var groups = dict.GroupBy(d => d.Value); // then, order those groups by the value var orderedGroups = groups.OrderBy(g => g.Key); // after that, you have all the KeyValuePairs that hold the MaxValue here: var maxKeys = orderedGroups.Last().ToList(); 

Have fun with it!

0
source

All Articles