在 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP