使用指定鍵和值在 C# 中插入 OrderedDictionary 中的一個新條目


要使用指定鍵和值在 OrderedDictionary 中插入一個新條目,程式碼如下 -

示例

 現場演示

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      dict.Add("7", "Seven");
      dict.Add("8", "Eight");
      Console.WriteLine("Elements...");
      IDictionaryEnumerator demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }
      dict.Insert(7, "15", "Fifteen");
      Console.WriteLine("Elements...UPDATED");
      demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }
   }
}

輸出

這將生成以下輸出 -

Elements...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 8, Value = Eight
Elements...UPDATED
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 15, Value = Fifteen
Key = 8, Value = Eight

示例

現在讓我們看另一個例子 -

 現場演示

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "Laptop");
      dict.Add("B", "Desktop");
      Console.WriteLine("Elements...");
      IDictionaryEnumerator demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }
      dict.Add("C", "Ultrabook");
      dict.Add("D", "Alienware");
      Console.WriteLine("
Elements...UPDATED");       demoEnum = dict.GetEnumerator();       while (demoEnum.MoveNext()) {          Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);       }       dict.Insert(2, "K", "Speakers");       Console.WriteLine("
Elements...UPDATED");       demoEnum = dict.GetEnumerator();       while (demoEnum.MoveNext()) {          Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);       }    } }

輸出

這將生成以下輸出 -

Elements...
Key = A, Value = Laptop
Key = B, Value = Desktop 

Elements...UPDATED
Key = A, Value = Laptop
Key = B, Value = Desktop
Key = C, Value = Ultrabook
Key = D, Value = Alienware 

Elements...UPDATED
Key = A, Value = Laptop
Key = B, Value = Desktop
Key = K, Value = Speakers
Key = C, Value = Ultrabook
Key = D, Value = Alienware

更新於: 11-12-2019

66 次瀏覽

開啟您的事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.