在C#中,您可以使用以下方法将字典初始化为(键,值,值)对:
Add
方法添加键值对。Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("key1", 1);
dictionary.Add("key2", 2);
dictionary.Add("key3", 3);
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["key1"] = 1;
dictionary["key2"] = 2;
dictionary["key3"] = 3;
Dictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 }
};
System.Linq
命名空间中的ToDictionary
方法将现有的键值对集合转换为字典。using System.Linq;
var keyValuePairs = new[]
{
new { Key = "key1", Value = 1 },
new { Key = "key2", Value = 2 },
new { Key = "key3", Value = 3 }
};
Dictionary<string, int> dictionary = keyValuePairs.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
在这些示例中,我们使用了string
类型的键和int
类型的值,但您可以根据需要使用其他类型。
领取专属 10元无门槛券
手把手带您无忧上云