在C#字典中添加键值对
要在C#词典中添加键值对,请首先声明一个词典。
IDictionary<int, string> d = new Dictionary<int, string>();
现在,使用KeyValuePair添加元素。
d.Add(new KeyValuePair<int, string>(1, "TVs")); d.Add(new KeyValuePair<int, string>(2, "Appliances")); d.Add(new KeyValuePair<int, string>(3, "Mobile"));
添加元素后,让我们显示键值对。
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IDictionary<int, string> d = new Dictionary<int, string>();
d.Add(new KeyValuePair<int, string>(1, "TVs"));
d.Add(new KeyValuePair<int, string>(2, "Appliances"));
d.Add(new KeyValuePair<int, string>(3, "Mobile"));
d.Add(new KeyValuePair<int, string>(4, "Tablet"));
d.Add(new KeyValuePair<int, string>(5, "Laptop"));
d.Add(new KeyValuePair<int, string>(6, "Desktop"));
d.Add(new KeyValuePair<int, string>(7, "Hard Drive"));
d.Add(new KeyValuePair<int, string>(8, "Flash Drive"));
foreach (KeyValuePair<int, string> ele in d) {
Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
}
}
}输出结果
Key = 1, Value = TVs Key = 2, Value = Appliances Key = 3, Value = Mobile Key = 4, Value = Tablet Key = 5, Value = Laptop Key = 6, Value = Desktop Key = 7, Value = Hard Drive Key = 8, Value = Flash Drive
热门推荐
10 祝贺新婚祝福语古代简短
11 生日幕后工作祝福语简短
12 给舍友送祝福语简短
13 给导师送花祝福语简短
14 中考祝福语简短高级句
15 虎年伊始祝福语大全简短
16 经典疫情祝福语大全简短
17 新年祝福语大全简短老师
18 预祝高尔夫的祝福语简短