獲取C#中StringDictionary鍵/值對的數量


要獲取StringDictionary中的鍵/值對數量,程式碼如下所示 −

示例

 線上演示

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict = new StringDictionary();
      strDict.Add("1", "One");
      strDict.Add("2", "Two");
      strDict.Add("3", "Three");
      strDict.Add("4", "Four");
      Console.WriteLine("StringDictionary key-value pairs...");
      IEnumerator demoEnum = strDict.GetEnumerator();
      DictionaryEntry d;
      while (demoEnum.MoveNext()) {
         d = (DictionaryEntry)demoEnum.Current;
         Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Count of StringDictionary key-value pairs..."+strDict.Count);
   }
}

輸出

這將產生以下輸出 −

StringDictionary key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Count of StringDictionary key-value pairs...4

示例

讓我們看另一個示例 −

 線上演示

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("A", "John");
      strDict1.Add("B", "Andy");
      strDict1.Add("C", "Tim");
      strDict1.Add("D", "Ryan");
      strDict1.Add("E", "Kevin");
      strDict1.Add("F", "Katie");
      strDict1.Add("G", "Brad");
      Console.WriteLine("StringDictionary1 elements...");
      foreach(DictionaryEntry de in strDict1){
         Console.WriteLine(de.Key + " " + de.Value);
      }
      Console.WriteLine("Count of StringDictionary1 key-value pairs..."+strDict1.Count);
      StringDictionary strDict2 = new StringDictionary();
      strDict2.Add("1", "A");
      strDict2.Add("2", "B");
      strDict2.Add("3", "C");
      strDict2.Add("4", "D");
      strDict2.Add("5", "E");
      Console.WriteLine("
StringDictionary2 key-value pairs...");       IEnumerator demoEnum = strDict2.GetEnumerator();       DictionaryEntry d;       while (demoEnum.MoveNext()) {          d = (DictionaryEntry)demoEnum.Current;          Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);       }       Console.WriteLine("Count of StringDictionary2 key-value pairs..."+strDict2.Count);    } }

輸出

這將產生以下輸出 −

StringDictionary1 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Count of StringDictionary1 key-value pairs...7

StringDictionary2 key-value pairs... Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E
Count of StringDictionary2 key-value pairs...5

更新於: 06-Dec-2019

67 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.