In C#, a key-value pair is typically represented using the KeyValuePair<TKey, TValue> structure. This structure is found in the System.Collections.Generic namespace.

Here is an example of how to use it:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store key-value pairs
        Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();

        // Add key-value pairs to the dictionary
        keyValuePairs.Add(1, "Value 1");
        keyValuePairs.Add(2, "Value 2");
        keyValuePairs.Add(3, "Value 3");

        // Access values using keys
        Console.WriteLine(keyValuePairs[1]); // Output: Value 1
        Console.WriteLine(keyValuePairs[2]); // Output: Value 2
        Console.WriteLine(keyValuePairs[3]); // Output: Value 3

        // Iterate over key-value pairs
        foreach (KeyValuePair<int, string> kvp in keyValuePairs)
        {
            Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
        }
    }
}

In the above example, we create a dictionary (keyValuePairs) that stores key-value pairs, where the key is of type int and the value is of type string. We then add some key-value pairs to the dictionary using the Add method.

To access the values in the dictionary, we can use the keys as indices. For example, keyValuePairs[1] will give us the value associated with the key 1.

We can also iterate over the key-value pairs in the dictionary using a foreach loop. Each element in the loop will be of type KeyValuePair<int, string>, allowing us to access both the key and the value of each pair

C# key value value

原文地址: https://www.cveoy.top/t/topic/ihL3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录