C# 中的 OrderedDictionary 類


OrderedDictionary 類表示一個鍵/值對的集合,可以透過鍵或索引訪問。

以下是 OrderedDictionary 類的屬性:

序號屬性 & 描述
1Count
獲取 OrderedDictionary 集合中包含的鍵/值對的數量。
2IsReadOnly
獲取一個值,指示 OrderedDictionary 集合是否為只讀。
3Item[Int32]
獲取或設定指定索引處的 value。
4Item[Object]
獲取或設定指定鍵的 value。
5Keys
獲取一個包含 OrderedDictionary 集合中鍵的 ICollection 物件。
6Values
獲取一個包含 OrderedDictionary 集合中值的 ICollection 物件。

以下是 OrderedDictionary 類的一些方法:

序號方法 & 描述
1Add(Object, Object)
使用指定的鍵和值將條目新增到 OrderedDictionary 集合中,並使用最低可用的索引。
2AsReadOnly()
返回當前 OrderedDictionary 集合的只讀副本。
3Clear()
移除 OrderedDictionary 集合中的所有元素。
4Contains(Object)
確定 OrderedDictionary 集合是否包含特定的鍵。
5CopyTo(Array, Int32)
將 OrderedDictionary 元素複製到指定索引處的一維 Array 物件。
6Equals(Object)
確定指定的 object 是否等於當前 object。(繼承自 Object)
7GetEnumerator()
返回一個 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

更新於: 2019-12-10

679 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.