How to Get Key-Value Pair with the Largest Value from a C# Dictionary

Published: Tuesday, May 3, 2022
Updated: Wednesday, May 4, 2022

Greetings, friends! Here is a simple approach for getting the key-value pair with the largest value from a dictionary in the C# language.

Copied! ⭐️
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
    public static void Main()
        Dictionary<string, int> d = new Dictionary<string, int>{{"red", 1}, {"green", 2}, {"blue", 3}};
        KeyValuePair<string, int> kvpWithMaxValue = d.Aggregate((a, b) => a.Value > b.Value ? a : b);

        // OUTPUT: [blue, 3]

You can try out this code by copying and pasting it to .NET Fiddle.

The Aggregate method is an extension method on the IEnumerable interface. This method is then implemented by the Enumerable class. The Dictionary class implements the IEnumerable interface, which means it gets access to the Aggregate extension method.

The word, "enumerable," means "countable." A Dictionary can have multiple key value pairs and thus can be "counted" or iterated over. The Aggregate method behaves like the Array.reduce function in JavaScript, and it can accept a Lambda expression.

The Aggregate method will iterate through every key-value pair in a dictionary and let you perform a comparison function between two values. In our scenario, the comparison function is checking to see which value of the key-value pair is bigger. It does this comparison across every key-value pair in the dictionary until you're left with the winner, the key-value pair with the largest value.