How is a key-value pair represented in C#?
In C#, you can use the Dictionary
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