Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การสร้าง StringDictionary ใน C#

ภาพรวม

StringDictionary ใน System.Collections.Specialized เป็น Dictionary เฉพาะสตริง (key และ value ต้องเป็น string) ไม่จัดเรียง คีย์ไม่ซ้ำ ไม่เป็น null

ตัวอย่างที่ 1: สร้างและเพิ่ม 7 คู่ แล้ววนลูปแสดง

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);
        }
    }
}

ผลลัพธ์

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

ตัวอย่างที่ 2: สร้าง 10 คู่ และเข้าถึงค่าด้วยคีย์โดยตรง

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"]);
    }
}

ผลลัพธ์

Value for key 5 = Notebook

สรุป

  • คีย์และค่าต้องเป็น string เท่านั้น (type-safe สำหรับสตริง)
  • คีย์ไม่สนใจ case (case-insensitive) - ตัวอย่างที่ 1 คีย์ "A" กลายเป็น "a"
  • เข้าถึงค่าได้ด้วย indexer: dict["key"]
  • ไม่จัดเรียง ลำดับขึ้นอยู่กับ hash code
  • สำหรับโค้ดใหม่ ควรใช้ Dictionary<string, string> แทน