The simplest way to get the key with the max value in a dictionary is to use the Linq MaxBy() method (added in .NET 6). This returns the key/value pair with the max value. Here’s an example:
using System.Linq;
var animalCountMap = new Dictionary<string, int>()
{
["fish"] = 100,
["dog"] = 3,
["cat"] = 10,
["bird"] = 50
};
var maxKVP = animalCountMap.MaxBy(kvp => kvp.Value);
var animal = maxKVP.Key;
var count = maxKVP.Value;
Console.WriteLine($"Animal seen the most: {animal} ({count})");
Code language: C# (cs)
Note: All examples shown initialize the dictionary with a small number of key/value pairs for readability.
This outputs the following:
Animal seen the most: fish (100)
Code language: plaintext (plaintext)
In this article, I’ll show examples of getting the max by key, min by key or value, and also show two alternative ways to do this without using MaxBy() (in case you’re on a version prior to .NET 6 or don’t want to use Linq).
Note: If you want just the max key or max value, and not the key/value pair, use d.Values.Max() or d.Keys.Max() instead of MaxBy().
Table of Contents
Max by key
Here’s an example of getting the key/value pair with the max key:
using System.Linq;
var zooAnimalVisitCount = new Dictionary<string, int>()
{
["antelope"] = 100,
["zebra"] = 10,
["bear"] = 3
};
var maxKVP = zooAnimalVisitCount.MaxBy(kvp => kvp.Key);
Console.WriteLine($"Last animal in zoo, {maxKVP.Key}, was visited {maxKVP.Value} time(s)");
Code language: C# (cs)
This outputs the following:
Last animal in zoo, zebra, was visited 10 time(s)
Code language: plaintext (plaintext)
While using Key or Value are the most common, you can actually get the max by some property of key or value. For example, let’s say you want to get longest key (using the same dictionary from above):
var maxKVP = zooAnimalVisitCount.MaxBy(kvp => kvp.Key.Length);
Console.WriteLine($"Animal with the longest name, {maxKVP.Key}, was visited {maxKVP.Value} time(s)");
Code language: C# (cs)
This outputs:
Animal with the longest name, antelope, was visited 100 time(s)
Code language: plaintext (plaintext)
Min by value
In addition to MaxBy(), there’s also MinBy(). Here’s an example of using MinBy() to get the key/value pair with the min value:
using System.Linq;
var animalCountMap = new Dictionary<string, int>()
{
["fish"] = 100,
["dog"] = 3,
["cat"] = 10,
["bird"] = 50
};
var minKVP = animalCountMap.MinBy(kvp => kvp.Value);
Console.WriteLine($"Animal seen the least: {minKVP.Key} ({minKVP.Value})");
Code language: C# (cs)
This outputs the following:
Animal seen the least: dog (3)
Code language: plaintext (plaintext)
Using Aggregate() to get the max by value (before .NET 6)
If you’re using a version before .NET 6, you can use the Linq Aggregate() method. This is referred to as Reduce in other languages. It takes a collection and reduces it down to a single value (such as the sum of values or the max value). Here’s an example of using Aggregate() to get the key/value pair with the max value:
using System.Linq;
var animalCountMap = new Dictionary<string, int>()
{
["fish"] = 100,
["dog"] = 3,
["cat"] = 1,
["bird"] = 500
};
var maxKVP = animalCountMap.Aggregate((left, right) => left.Value > right.Value ? left : right);
var animal = maxKVP.Key;
var count = maxKVP.Value;
Console.WriteLine($"Animal seen the most: {animal} ({count})");
Code language: C# (cs)
This outputs:
Animal seen the most: bird (500)
Code language: plaintext (plaintext)
The syntax is a little hard to understand if you want a one-liner approach like this. The next section shows how to do this with a loop, which is more verbose, but uses simpler syntax.
Looping to find the max value
Instead of using Linq methods, you can loop through the dictionary to find the max value. This is approximately 2x faster than using Linq.
Here’s an example:
var animalCountMap = new Dictionary<string, int>()
{
["fish"] = 100,
["dog"] = 3,
["cat"] = 1,
["bird"] = 500
};
var maxKVP = KeyValuePair.Create(string.Empty, int.MinValue);
foreach(var kvp in animalCountMap)
{
if (kvp.Value >= maxKVP.Value)
maxKVP = kvp;
}
//note: Use >= instead of >, otherwise this returns the wrong thing when all values == int.MinValue
var animal = maxKVP.Key;
var count = maxKVP.Value;
Console.WriteLine($"Animal seen the most: {animal} ({count})");
Code language: C# (cs)
Note: Using KeyValuePair.Create() with minimum defaults is 2-3x faster than using .First() to initialize the max KeyValuePair. It’s faster because it avoids starting an unnecessary enumeration (even though it seems like .First() should be fast, it’s not).
This outputs the following:
Animal seen the most: bird (500)