ZetCode

C# KeyValuePair

last modified November 15, 2026

This tutorial shows how to work with the KeyValuePair<TKey, TValue> struct in C#. We create pairs, read them from dictionaries, deconstruct them, process them with LINQ, and compare them with tuples.

KeyValuePair<TKey, TValue> is a generic struct from the System.Collections.Generic namespace. It holds two values: a Key and a Value. Both properties are read-only, so a pair cannot be changed after it is created.

The struct is the element type of dictionaries. When we enumerate a Dictionary<TKey, TValue>, a SortedDictionary<TKey, TValue>, or any other IDictionary<TKey, TValue>, each entry comes as a KeyValuePair. Pairs are also handy for ordered lists of entries in which a key can appear more than once.

Creating pairs

A pair is created with its constructor or with the KeyValuePair.Create factory method, which infers the type arguments from the values.

Program.cs
KeyValuePair<string, int> p1 = new("apples", 50);
var p2 = new KeyValuePair<string, int>("oranges", 30);
var p3 = KeyValuePair.Create("bananas", 45);

Console.WriteLine($"{p1.Key}: {p1.Value}");
Console.WriteLine($"{p2.Key}: {p2.Value}");
Console.WriteLine($"{p3.Key}: {p3.Value}");

Console.WriteLine(p1);
Console.WriteLine(p3.GetType());

We create three pairs and print their keys and values.

KeyValuePair<string, int> p1 = new("apples", 50);
var p2 = new KeyValuePair<string, int>("oranges", 30);

The type arguments specify the type of the key and the value. With a target-typed new expression the types are written only once.

var p3 = KeyValuePair.Create("bananas", 45);

The non-generic KeyValuePair static class has a Create method. The compiler infers KeyValuePair<string, int> from the arguments.

Console.WriteLine(p1);

The ToString method formats a pair as [key, value].

$ dotnet run
apples: 50
oranges: 30
bananas: 45
[apples, 50]
System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]

Pairs in dictionaries

Enumerating a dictionary produces KeyValuePair elements. Since C# 7 and .NET Core 2.0, a pair can be deconstructed into two variables right in the foreach statement.

Program.cs
Dictionary<string, int> stock = new()
{
    ["apples"] = 50,
    ["oranges"] = 30,
    ["bananas"] = 45,
    ["grapes"] = 25
};

foreach (KeyValuePair<string, int> item in stock)
{
    Console.WriteLine($"{item.Key}: {item.Value}");
}

Console.WriteLine("----------------");

foreach (var (fruit, qty) in stock)
{
    Console.WriteLine($"{fruit,-8} {qty,3}");
}

We go over a dictionary of fruit quantities twice: first with explicit pairs, then with deconstruction.

foreach (KeyValuePair<string, int> item in stock)

Each element of the dictionary is a KeyValuePair<string, int>; we read its Key and Value properties. In practice the type is often written as var.

foreach (var (fruit, qty) in stock)

The Deconstruct method of the struct splits each pair into the fruit and qty variables. The names describe the data better than Key and Value.

$ dotnet run
apples: 50
oranges: 30
bananas: 45
grapes: 25
----------------
apples    50
oranges   30
bananas   45
grapes    25

The default pair

Because KeyValuePair is a struct, LINQ methods such as FirstOrDefault return default when nothing matches. The default pair has a null key and a zero value, which is easy to mistake for real data.

Program.cs
Dictionary<string, int> stock = new()
{
    ["apples"] = 50,
    ["oranges"] = 30
};

var found = stock.FirstOrDefault(e => e.Key == "kiwis");
Console.WriteLine($"FirstOrDefault: {found}");
Console.WriteLine(found.Key is null);

KeyValuePair<string, int> empty = default;
Console.WriteLine(found.Equals(empty));

if (stock.TryGetValue("kiwis", out int qty))
{
    Console.WriteLine($"kiwis: {qty}");
}
else
{
    Console.WriteLine("no kiwis in stock");
}

if (stock.TryGetValue("apples", out qty))
{
    Console.WriteLine($"apples: {qty}");
}

We search a dictionary for a missing key in two ways.

var found = stock.FirstOrDefault(e => e.Key == "kiwis");

There is no kiwis key, so FirstOrDefault returns default(KeyValuePair<string, int>). It prints as [, 0]. Besides being ambiguous, the search goes through all entries one by one.

if (stock.TryGetValue("kiwis", out int qty))

TryGetValue is the right tool for a lookup by key. It uses the hash table, so the lookup is fast, and its bool result tells us clearly whether the key exists.

$ dotnet run
FirstOrDefault: [, 0]
True
True
no kiwis in stock
apples: 50

Lists of pairs

A List<KeyValuePair<TKey, TValue>> keeps the entries in insertion order and allows duplicate keys. A dictionary allows neither.

Program.cs
List<KeyValuePair<string, int>> scores =
[
    new("Alice", 82),
    new("Bob", 75),
    new("Alice", 91),
    new("Carol", 68)
];

foreach (var (name, score) in scores)
{
    Console.WriteLine($"{name}: {score}");
}

var best = scores
    .GroupBy(e => e.Key)
    .ToDictionary(g => g.Key, g => g.Max(e => e.Value));

Console.WriteLine(string.Join(", ", best));

try
{
    var dict = new Dictionary<string, int>(scores);
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

We store test scores in a list in which a student can appear more than once.

var best = scores
    .GroupBy(e => e.Key)
    .ToDictionary(g => g.Key, g => g.Max(e => e.Value));

To turn the list into a dictionary, we first group the pairs by key and keep the best score of each student.

var dict = new Dictionary<string, int>(scores);

The Dictionary constructor accepts a collection of pairs. With a duplicate key it throws an ArgumentException.

$ dotnet run
Alice: 82
Bob: 75
Alice: 91
Carol: 68
[Alice, 91], [Bob, 75], [Carol, 68]
An item with the same key has already been added. Key: Alice

Pairs and LINQ

A dictionary is an IEnumerable<KeyValuePair<TKey, TValue>>, so all LINQ operators work on it. The lambdas receive pairs.

Program.cs
Dictionary<string, decimal> prices = new()
{
    ["laptop"] = 999.99m,
    ["phone"] = 699.99m,
    ["tablet"] = 349.99m,
    ["monitor"] = 249.99m
};

Console.WriteLine("Sorted by price:");

foreach (var (item, price) in prices.OrderByDescending(e => e.Value))
{
    Console.WriteLine($"{item,-8} {price,8:F2}");
}

KeyValuePair<string, decimal> cheapest = prices.MinBy(e => e.Value);
Console.WriteLine($"Cheapest: {cheapest.Key} at {cheapest.Value:F2}");

var expensive = prices.Where(e => e.Value > 500m).Select(e => e.Key);
Console.WriteLine($"Over 500: {string.Join(", ", expensive)}");

var sorted = new SortedDictionary<string, decimal>(prices);
Console.WriteLine($"First by name: {sorted.First()}");

We sort a dictionary of prices, find the cheapest item, and filter the expensive ones.

foreach (var (item, price) in prices.OrderByDescending(e => e.Value))

A dictionary has no order of its own. OrderByDescending returns its pairs sorted by value, and we deconstruct each of them.

KeyValuePair<string, decimal> cheapest = prices.MinBy(e => e.Value);

MinBy returns the whole pair with the smallest value, not just the value. It does not need to sort the collection.

var expensive = prices.Where(e => e.Value > 500m).Select(e => e.Key);

We filter the pairs by value and project them to their keys.

var sorted = new SortedDictionary<string, decimal>(prices);

A SortedDictionary keeps its pairs ordered by key. Its First element is the pair with the alphabetically first key.

$ dotnet run
Sorted by price:
laptop     999.99
phone      699.99
tablet     349.99
monitor    249.99
Cheapest: monitor at 249.99
Over 500: laptop, phone
First by name: [laptop, 999.99]

Pairs are immutable

The Key and Value properties have no setters. An assignment such as pair.Key = "b" fails with error CS0200. To change a value, we write it back to the dictionary or create a new pair.

Program.cs
Dictionary<string, int> stock = new()
{
    ["apples"] = 50,
    ["oranges"] = 30,
    ["bananas"] = 0
};

foreach (var (fruit, qty) in stock)
{
    stock[fruit] = qty + 10;
}

Console.WriteLine(string.Join(", ", stock));

var pair = KeyValuePair.Create("plums", 12);
var changed = KeyValuePair.Create(pair.Key, pair.Value * 2);

Console.WriteLine($"{pair} {changed}");

var a = KeyValuePair.Create("x", 1);
var b = KeyValuePair.Create("x", 1);
Console.WriteLine(a.Equals(b));

We increase the quantities in a dictionary, derive a new pair from an existing one, and compare two pairs.

foreach (var (fruit, qty) in stock)
{
    stock[fruit] = qty + 10;
}

The pairs that the loop receives are copies. We update the entries through the dictionary indexer. Since .NET Core 3.0, overwriting the value of an existing key (and removing entries) during enumeration is allowed; adding a new key would throw an InvalidOperationException on the next step.

var changed = KeyValuePair.Create(pair.Key, pair.Value * 2);

A modified pair is a new pair built from the old one.

Console.WriteLine(a.Equals(b));

KeyValuePair does not override Equals, so the reflection-based ValueType.Equals compares the fields. It does not define the == operator; a == b gives error CS0019.

$ dotnet run
[apples, 60], [oranges, 40], [bananas, 10]
[plums, 12] [plums, 24]
True

KeyValuePair versus tuples

Older code sometimes returns two values from a method as a KeyValuePair. A named value tuple is a better fit: its elements have meaningful names, it supports ==, and it is not limited to two values.

Program.cs
int[] vals = [12, 45, 7, 32, 19, 3, 56];

KeyValuePair<int, int> kvp = MinMaxPair(vals);
Console.WriteLine($"min: {kvp.Key}, max: {kvp.Value}");

var (min, max) = MinMaxTuple(vals);
Console.WriteLine($"min: {min}, max: {max}");

var t = MinMaxTuple(vals);
Console.WriteLine(t == (3, 56));

KeyValuePair<int, int> MinMaxPair(int[] data) => new(data.Min(), data.Max());

(int Min, int Max) MinMaxTuple(int[] data) => (data.Min(), data.Max());

We return the minimum and maximum of an array, once as a pair and once as a tuple.

KeyValuePair<int, int> MinMaxPair(int[] data) => new(data.Min(), data.Max());

The pair works, but Key for the minimum and Value for the maximum say nothing about the data.

(int Min, int Max) MinMaxTuple(int[] data) => (data.Min(), data.Max());

The tuple names its elements Min and Max. The caller can deconstruct it or compare it with another tuple using ==. Keep KeyValuePair for dictionary entries and for APIs that expect it.

$ dotnet run
min: 3, max: 56
min: 3, max: 56
True

Source

KeyValuePair<TKey, TValue> struct - reference

Dictionary<TKey, TValue> class - reference

In this article we have worked with the KeyValuePair struct in C#. See also the Dictionary, tuple, and deconstruct tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.