C# 中的 OrderedDictionary 類
OrderedDictionary 類表示一個鍵/值對的集合,可以透過鍵或索引訪問。
以下是 OrderedDictionary 類的屬性:
| 序號 | 屬性 & 描述 |
|---|---|
| 1 | Count 獲取 OrderedDictionary 集合中包含的鍵/值對的數量。 |
| 2 | IsReadOnly 獲取一個值,指示 OrderedDictionary 集合是否為只讀。 |
| 3 | Item[Int32] 獲取或設定指定索引處的 value。 |
| 4 | Item[Object] 獲取或設定指定鍵的 value。 |
| 5 | Keys 獲取一個包含 OrderedDictionary 集合中鍵的 ICollection 物件。 |
| 6 | Values 獲取一個包含 OrderedDictionary 集合中值的 ICollection 物件。 |
以下是 OrderedDictionary 類的一些方法:
| 序號 | 方法 & 描述 |
|---|---|
| 1 | Add(Object, Object) 使用指定的鍵和值將條目新增到 OrderedDictionary 集合中,並使用最低可用的索引。 |
| 2 | AsReadOnly() 返回當前 OrderedDictionary 集合的只讀副本。 |
| 3 | Clear() 移除 OrderedDictionary 集合中的所有元素。 |
| 4 | Contains(Object) 確定 OrderedDictionary 集合是否包含特定的鍵。 |
| 5 | CopyTo(Array, Int32) 將 OrderedDictionary 元素複製到指定索引處的一維 Array 物件。 |
| 6 | Equals(Object) 確定指定的 object 是否等於當前 object。(繼承自 Object) |
| 7 | GetEnumerator() 返回一個 IDictionaryEnumerator 物件,該物件遍歷 OrderedDictionary 集合。 |
現在讓我們看一些例子:
示例
要獲取 OrderedDictionary 中包含的鍵/值對的數量,程式碼如下:
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Home Appliances");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary elements...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.Clear();
Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
}
}輸出
這將產生以下輸出:
OrderedDictionary elements... A Home Appliances B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of elements in OrderedDictionary = 6 Count of elements in OrderedDictionary (Updated)= 0
示例
要移除 OrderedDictionary 中的所有元素,程式碼如下:
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Books");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary elements...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.Clear();
Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
}
}輸出
這將產生以下輸出:
OrderedDictionary elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of elements in OrderedDictionary = 6 Count of elements in OrderedDictionary (Updated)= 0
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP