How to Get key with the max value in a dictionary in C#
By FoxLearn 3/6/2025 9:06:16 AM 18
This method returns the key/value pair with the highest value.
using System.Linq; var productPriceMap = new Dictionary<string, decimal>() { ["Laptop"] = 999.99, ["Smartphone"] = 599.99, ["Tablet"] = 299.99, ["Smartwatch"] = 199.99 }; var maxKVP = productPriceMap.MaxBy(kvp => kvp.Value); var product = maxKVP.Key; var price = maxKVP.Value; Console.WriteLine($"Most expensive product: {product} (${price})");
Output:
Most expensive product: Laptop ($999.99)
In this article, I’ll provide examples of obtaining the max by key, min by key or value, and demonstrate two alternative methods to achieve this without using MaxBy() (for those on versions prior to .NET 6 or who prefer not to use Linq).
Note: If you want just the max key or max value without the key/value pair, use d.Values.Max()
or d.Keys.Max()
instead of MaxBy().
Max by Key
Here’s an example of retrieving the key/value pair with the maximum key:
using System.Linq; var inventoryCountMap = new Dictionary<string, int>() { ["Pencils"] = 150, ["Notebooks"] = 75, ["Markers"] = 25 }; var maxKVP = inventoryCountMap.MaxBy(kvp => kvp.Key); Console.WriteLine($"Last item in inventory: {maxKVP.Key}, quantity: {maxKVP.Value}");
Output:
Last item in inventory: Pencils, quantity: 150
Min by Value
In addition to MaxBy(), there’s also MinBy().
For example, How to use MinBy() to get the key/value pair with the minimum value:
var minKVP = productPriceMap.MinBy(kvp => kvp.Value); Console.WriteLine($"Least expensive product: {minKVP.Key} (${minKVP.Value})");
Output:
Least expensive product: Smartwatch ($199.99)
Using Aggregate() to Get the Max by Value (Before .NET 6)
If you’re on a version before .NET 6, you can use the Linq Aggregate() method. Here’s an example of using Aggregate() to find the key/value pair with the max value:
var maxKVP = productPriceMap.Aggregate((left, right) => left.Value > right.Value ? left : right); var product = maxKVP.Key; var price = maxKVP.Value; Console.WriteLine($"Most expensive product: {product} (${price})");
Output:
Most expensive product: Laptop ($999.99)
Looping to Find the Max Value
Instead of using Linq methods, you can also loop through the dictionary to find the max value, which can be faster.
var maxKVP = KeyValuePair.Create(string.Empty, decimal.MinValue); foreach(var kvp in productPriceMap) { if (kvp.Value >= maxKVP.Value) maxKVP = kvp; } var product = maxKVP.Key; var price = maxKVP.Value; Console.WriteLine($"Most expensive product: {product} (${price})");
Output:
Most expensive product: Laptop ($999.99)
- How to Get Status Codes with HttpClient in C#
- How to use TimeZoneInfo in C#
- How to Get and send JSON with HttpClient in C#
- How to Deserialize JSON as a stream in C#
- How to use JsonNode in C#
- TimeZoneInfo with current UTC offset in C#
- How to Parser a CSV file in C#
- How to read configuration from appsettings.json in C#