KeyValuePair<TKey, TValue> Struct

System.Collections.Generic

Represents a key/value pair that can be returned by a dictionary.

Summary

The KeyValuePair<TKey, TValue> structure is a simple immutable type that holds a key and its corresponding value. It is commonly used as the return type of the enumerator for dictionaries (like Dictionary<TKey, TValue>), providing access to individual elements within the collection.

Syntax

public struct KeyValuePair<TKey, TValue> : IEquatable<KeyValuePair<TKey, TValue>>
        

Type Parameters

Constructors

KeyValuePair(TKey key, TValue value)

Initializes a new instance of the KeyValuePair<TKey, TValue> structure with the specified key and value.

public KeyValuePair(TKey key, TValue value);

Properties

Key

Gets the key of the key/value pair.

public TKey Key { get; }

Value

Gets the value of the key/value pair.

public TValue Value { get; }

Methods

Equals(object other)

Determines whether the specified object is equal to the current object.

public override bool Equals(object other);

Equals(KeyValuePair<TKey, TValue> other)

Determines whether the specified KeyValuePair<TKey, TValue> is equal to the current KeyValuePair<TKey, TValue>.

public bool Equals(KeyValuePair<TKey, TValue> other);

GetHashCode()

Returns the hash code for the current instance.

public override int GetHashCode();

ToString()

Returns a string representation of the current object.

public override string ToString();

Operators

Equality operator ==

Compares two KeyValuePair<TKey, TValue> structures for equality.

public static bool operator ==(KeyValuePair<TKey, TValue> left, KeyValuePair<TKey, TValue> right);

Inequality operator !=

Compares two KeyValuePair<TKey, TValue> structures for inequality.

public static bool operator !=(KeyValuePair<TKey, TValue> left, KeyValuePair<TKey, TValue> right);

Example

Using KeyValuePair with a Dictionary

The following example demonstrates how to iterate through a Dictionary<string, int> and access its key-value pairs using KeyValuePair<TKey, TValue>.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        Dictionary<string, int> ages = new Dictionary<string, int>();
        ages.Add("Alice", 30);
        ages.Add("Bob", 25);
        ages.Add("Charlie", 35);

        Console.WriteLine("Dictionary Contents:");
        foreach (KeyValuePair<string, int> pair in ages)
        {
            Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
        }
    }
}