C# KeyValuePair Tutorial
last modified May 13, 2025
The KeyValuePair struct in C# is a fundamental data structure that represents a key-value pair. It's commonly used with dictionaries and other collection types to store paired elements. This tutorial explores KeyValuePair in depth.
KeyValuePair
is a generic struct defined in the
System.Collections.Generic namespace. It encapsulates two related elements: a
key and a value.
This structure is primarily used when working with dictionaries, but can also be employed in other scenarios where you need to associate two values together. It's a lightweight, immutable structure that provides efficient storage.
KeyValuePair
is particularly useful when you need to enumerate
through dictionary entries or when you need to return a single key-value pair
from a method.
Basic KeyValuePair Example
This example demonstrates the most basic usage of KeyValuePair, creating instances and accessing their properties.
KeyValuePair<string, int> product1 = new ("Apples", 50); var product2 = new KeyValuePair<string, int>("Oranges", 30); Console.WriteLine($"Product: {product1.Key}, Quantity: {product1.Value}"); Console.WriteLine($"Product: {product2.Key}, Quantity: {product2.Value}"); DisplayKeyValuePair(product1); void DisplayKeyValuePair(KeyValuePair<string, int> pair) { Console.WriteLine($"In method - Key: {pair.Key}, Value: {pair.Value}"); }
This code shows how to create KeyValuePair
instances and access
their Key and Value properties. It also demonstrates passing KeyValuePair to
methods.
KeyValuePair<string, int> product1 = new ("Apples", 50);
Creates a KeyValuePair
with string key "Apples" and integer value
50. The generic parameters specify the types of the key and value.
var product2 = new KeyValuePair<string, int>("Oranges", 30);
Uses var keyword for implicit typing. The compiler infers the type from the right-hand side of the assignment.
Console.WriteLine($"Product: {product1.Key}, Quantity: {product1.Value}");
Accesses the Key and Value properties of the KeyValuePair instance. These properties are read-only.
KeyValuePair with Dictionaries
KeyValuePair is most commonly encountered when working with dictionaries. This example shows how to use it when iterating through dictionary entries.
Dictionary<string, int> inventory = new() { {"Apples", 50}, {"Oranges", 30}, {"Bananas", 45}, {"Grapes", 25} }; Console.WriteLine("Inventory Contents:"); foreach (KeyValuePair<string, int> item in inventory) { Console.WriteLine($"{item.Key}: {item.Value} units"); } KeyValuePair<string, int> bananaItem = inventory.FirstOrDefault( x => x.Key == "Bananas"); if (bananaItem.Key != null) { Console.WriteLine($"\nFound: {bananaItem.Key} - {bananaItem.Value}"); }
This example demonstrates using KeyValuePair with dictionaries, including iteration and searching operations.
foreach (KeyValuePair<string, int> item in inventory)
When enumerating a dictionary, each element is a KeyValuePair containing the key and value for that entry. This is the primary use case for KeyValuePair.
KeyValuePair<string, int> bananaItem = inventory.FirstOrDefault( x => x.Key == "Bananas");
Uses LINQ's FirstOrDefault
to find a specific
KeyValuePair
in the dictionary. Note that we check if the Key is
null to determine if the item was found.
KeyValuePair in Method Returns
KeyValuePair can be useful as a return type when you need to return two related values from a method. This example shows this pattern.
int[] numbers = { 12, 45, 7, 32, 19, 3, 56 }; var minMax = FindMinMax(numbers); Console.WriteLine($"Minimum: {minMax.Key}, Maximum: {minMax.Value}"); var result = TryParseNumber("42"); if (result.Key) { Console.WriteLine($"Parsed successfully: {result.Value}"); } KeyValuePair<int, int> FindMinMax(int[] numbers) { if (numbers == null || numbers.Length == 0) { throw new ArgumentException("Array cannot be empty"); } int min = numbers[0]; int max = numbers[0]; foreach (int num in numbers) { if (num < min) min = num; if (num > max) max = num; } return new KeyValuePair<int, int>(min, max); } KeyValuePair<bool, int> TryParseNumber(string input) { bool success = int.TryParse(input, out int result); return new KeyValuePair<bool, int>(success, result); }
This code demonstrates two common patterns for using KeyValuePair
as a return type: returning related values (min/max) and implementing a TryParse
pattern.
KeyValuePair<int, int> FindMinMax(int[] numbers)
Method returns two related integers (min and max) bundled in a KeyValuePair. This is cleaner than using out parameters in some cases.
KeyValuePair<bool, int> TryParseNumber(string input)
Implements a TryParse pattern using KeyValuePair, returning both a success flag and the parsed value. Similar to how int.TryParse works with out params.
Advanced KeyValuePair Usage
This example shows more advanced scenarios including deconstruction, LINQ operations, and custom comparisons with KeyValuePair.
Dictionary<string, decimal> productPrices = new() { {"Laptop", 999.99m}, {"Phone", 699.99m}, {"Tablet", 349.99m}, {"Monitor", 249.99m} }; foreach (var (product, price) in productPrices) { Console.WriteLine($"{product} costs {price:C}"); } var expensiveItems = productPrices .Where(kvp => kvp.Value > 500m) .OrderByDescending(kvp => kvp.Value); Console.WriteLine("\nExpensive Items:"); foreach (var item in expensiveItems) { Console.WriteLine($"{item.Key}: {item.Value:C}"); } KeyValuePair<string, decimal> mostExpensive = productPrices .OrderByDescending(kvp => kvp.Value) .First(); Console.WriteLine($"\nMost expensive: {mostExpensive.Key} at {mostExpensive.Value:C}");
This example demonstrates modern C# features like deconstruction, LINQ operations, and custom sorting with KeyValuePair.
foreach (var (product, price) in productPrices)
Uses deconstruction syntax to break the KeyValuePair into separate variables. This is available in C# 7.0 and later for cleaner code.
.Where(kvp => kvp.Value > 500m) .OrderByDescending(kvp => kvp.Value);
Shows LINQ operations filtering and sorting based on the Value property of the KeyValuePairs in the dictionary.
KeyValuePair<string, decimal> mostExpensive = productPrices .OrderByDescending(kvp => kvp.Value) .First();
Finds the most expensive item by sorting by value and taking the first item. Demonstrates how KeyValuePair can be used in custom comparison operations.
Source
Microsoft KeyValuePair Documentation
KeyValuePair is a versatile structure that provides a clean way to work with paired data in C#. It's particularly useful with dictionaries but has broader applications as shown in these examples.
Author
List all C# tutorials.