How is a key-value pair represented in C#?

In C#, you can use the Dictionary class to represent key-value pairs. The Dictionary class represents a collection of keys and values, where each key is unique and corresponds to a single value. Here is a simple example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> keyValuePairs = new Dictionary<string, int>();

        // 添加键值对
        keyValuePairs.Add("Alice", 25);
        keyValuePairs.Add("Bob", 30);
        keyValuePairs.Add("Charlie", 35);

        // 访问键值对
        Console.WriteLine(keyValuePairs["Alice"]); // 输出 25

        // 遍历所有键值对
        foreach (var kvp in keyValuePairs)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }
}

In the example above, we used the class Dictionary to represent a collection of key-value pairs where the key is a string and the value is an integer. We added some key-value pairs and demonstrated how to access and iterate through them.

bannerAds