C# Reference ยท Collections
KeyValuePair<TKey,TValue>
Reference for C# KeyValuePair<TKey,TValue>: the struct a Dictionary yields when enumerated, how to create and deconstruct pairs and when a tuple is better.
KeyValuePair<TKey,TValue> is a small immutable struct that holds one key and one value. You meet it most often when you enumerate a Dictionary<TKey,TValue>, because each element of the dictionary is a pair. You can also create pairs yourself, put them in a list, or pass them to methods such as Dictionary.Add overloads and Enumerable.ToDictionary.
Since .NET Core 2.0 a pair can be deconstructed with var (key, value) = pair, and KeyValuePair.Create(key, value) builds one with type inference.
var pair = KeyValuePair.Create("age", 31); var (key, value) = pair;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public readonly struct KeyValuePair<TKey, TValue> { public KeyValuePair(TKey key, TValue value); public TKey Key { get; } public TValue Value { get; } public void Deconstruct(out TKey key, out TValue value); } public static class KeyValuePair { public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value); }
| Name | Description |
|---|---|
Key |
The key. Read-only. |
Value |
The value. Read-only. |
Create |
Builds a pair and lets the compiler infer both type arguments. |
Returns: ToString() returns [key, value], with each part converted to text (an empty string for null).
Usage notes
- A pair is immutable: you cannot assign
pair.Value. To change what a dictionary stores, writedict[key] = newValue. - It is a value type, so copies are independent of the dictionary. After you change
stock["apples"], a pair you took earlier still holds the old value. - The default pair has a
nullkey (for reference key types) and a default value. - Keys in a
Dictionaryare unique; aList<KeyValuePair<,>>orIEnumerable<KeyValuePair<,>>can hold duplicates and has no lookup, so finding a key is O(n). - Choose a named tuple such as
(string Name, int Qty)when you want meaningful property names; a pair always saysKeyandValue. Records are better when the data has a domain meaning. KeyValuePair<TKey,TValue>is not related toDictionaryEntry(non-genericHashtable) or toLookupgroupings.- Do not use a mutable object as a key: changing it after insertion breaks hash lookups.