0
0
CsharpHow-ToBeginner · 3 min read

How to Find Max Value in Dictionary in C#

To find the maximum value in a Dictionary in C#, use LINQ's Max() method on the dictionary's Values collection. For example, int maxValue = myDict.Values.Max(); returns the highest value stored in the dictionary.
📐

Syntax

Use LINQ's Max() method on the dictionary's Values property to get the maximum value.

  • myDict: Your dictionary variable.
  • Values: Collection of all values in the dictionary.
  • Max(): LINQ method that returns the largest value.
csharp
int maxValue = myDict.Values.Max();
💻

Example

This example shows how to create a dictionary, add some key-value pairs, and find the maximum value using LINQ.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, int> scores = new Dictionary<string, int>()
        {
            {"Alice", 85},
            {"Bob", 92},
            {"Charlie", 78},
            {"Diana", 95}
        };

        int maxScore = scores.Values.Max();
        Console.WriteLine($"The highest score is {maxScore}.");
    }
}
Output
The highest score is 95.
⚠️

Common Pitfalls

Empty Dictionary: Calling Max() on an empty dictionary's values causes an exception. Always check if the dictionary has elements before calling Max().

Finding Key of Max Value: Max() returns only the value, not the key. To get the key with the max value, use OrderByDescending or Aggregate.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Dictionary<string, int> data = new Dictionary<string, int>();

        // Wrong: This will throw InvalidOperationException if dictionary is empty
        // int maxVal = data.Values.Max();

        // Right: Check if dictionary is not empty
        if (data.Any())
        {
            int maxVal = data.Values.Max();
            Console.WriteLine($"Max value: {maxVal}");
        }
        else
        {
            Console.WriteLine("Dictionary is empty.");
        }

        // To get key with max value
        var maxPair = data.OrderByDescending(kvp => kvp.Value).FirstOrDefault();
        if (!maxPair.Equals(default(KeyValuePair<string, int>)))
        {
            Console.WriteLine($"Key with max value: {maxPair.Key}, Value: {maxPair.Value}");
        }
    }
}
Output
Dictionary is empty.
📊

Quick Reference

Summary tips for finding max value in a dictionary:

  • Use myDict.Values.Max() to get the highest value.
  • Check if dictionary is not empty before calling Max().
  • To find the key with the max value, use OrderByDescending or Aggregate.

Key Takeaways

Use LINQ's Max() on dictionary.Values to find the maximum value.
Always check if the dictionary is not empty before calling Max() to avoid errors.
To get the key with the maximum value, use OrderByDescending or Aggregate methods.
Max() returns only the value, not the key.
Dictionary.Values gives a collection of all values for LINQ operations.