Light Mode Image

C# KeyValue Pair

A KeyValuePair<TKey, TValue> is a struct that represents a generic key-value pair. It is commonly used in scenarios where you need to work with a collection of key-value pairs, such as dictionaries.

 

The KeyValuePair<TKey, TValue> struct is part of the System.Collections.Generic namespace.

 

Example of KeyValuePair<TKey, TValue> in C#.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a KeyValuePair
        KeyValuePair<string, int> keyValue = new KeyValuePair<string, int>("Age", 25);

        // Accessing Key and Value
        string key = keyValue.Key;
        int value = keyValue.Value;

        // Displaying Key and Value
        Console.WriteLine($"Key: {key}, Value: {value}");
    }
}

 

In practical usage, KeyValuePair<TKey, TValue> is often used in the context of dictionaries.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a Dictionary using KeyValuePair
        Dictionary<string, int> myDictionary = new Dictionary<string, int>
        {
            {"Alice", 30},
            {"Bob", 25},
            {"Charlie", 35}
        };

        // Iterating through the dictionary using KeyValuePair
        foreach (KeyValuePair<string, int> kvp in myDictionary)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

 

Starting from C# 7.0, you can use tuple deconstruction to simplify the iteration over key-value pairs in dictionaries.

foreach ((string key, int value) in myDictionary)
{
    Console.WriteLine($"Key: {key}, Value: {value}");
}

 

This provides a more concise syntax for working with key-value pairs.