Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để tạo một StringDictionary trong C #?

Để tạo một StringDictionary trong C #, mã như sau -

Ví dụ

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringDictionary strDict = new StringDictionary();
      strDict.Add("A", "John");
      strDict.Add("B", "Andy");
      strDict.Add("C", "Tim");
      strDict.Add("D", "Ryan");
      strDict.Add("E", "Kevin");
      strDict.Add("F", "Katie");
      strDict.Add("G", "Brad");
      Console.WriteLine("StringDictionary elements...");
      foreach(DictionaryEntry de in strDict) {
         Console.WriteLine(de.Key + " " + de.Value);
      }
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

StringDictionary elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

Ví dụ

Hãy để chúng tôi xem một ví dụ khác -

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringDictionary myDict = new StringDictionary();
      myDict.Add("1", "Tablet");
      myDict.Add("2", "Desktop");
      myDict.Add("3", "Speakers");
      myDict.Add("4", "Laptop");
      myDict.Add("5", "Notebook");
      myDict.Add("6", "Ultrabook");
      myDict.Add("7", "HDD");
      myDict.Add("8", "SDD");
      myDict.Add("9", "Headphone");
      myDict.Add("10", "Earphone");
      Console.WriteLine("Value for key 5 = "+myDict["5"]);
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Value for key 5 = Notebook