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

เพิ่มคีย์และค่าใน StringDictionary ใน C#

StringDictionary เป็นคลาสใน System.Collections.Specialized ที่ออกแบบมาสำหรับเก็บคีย์-ค่าที่ทั้งคู่เป็นสตริง (string key, string value) ใช้เมธอด Add(key, value) ในการเพิ่มข้อมูล คีย์จะถูกแปลงเป็น lowercase อัตโนมัติ

ตัวอย่างโค้ด

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

ตัวอย่างเพิ่มเติม

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringDictionary strDict = new StringDictionary();
        strDict.Add("1", "Electric Cars");
        strDict.Add("2", "SUV");
        strDict.Add("3", "AUV");

        Console.WriteLine("StringDictionary elements...");
        foreach (DictionaryEntry de in strDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
    }
}

ผลลัพธ์

StringDictionary elements...
1 Electric Cars
2 SUV
3 AUV

คุณสมบัติสำคัญของ StringDictionary

  • คีย์ถูกแปลงเป็น lowercase อัตโนมัติ - "A" จะกลายเป็น "a"
  • คีย์ต้องเป็น string เท่านั้น (ไม่ใช่ object)
  • ค่าต้องเป็น string เท่านั้น
  • คีย์ ไม่ซ้ำกัน (unique) - เพิ่มคีย์ซ้ำจะโยน ArgumentException
  • ไม่รักษาลำดับการเพิ่ม (unordered) - ใช้ hashtable ด้านใน
  • มีเมธอด: Add, Remove, ContainsKey, ContainsValue, Clear, Item[key] (indexer)

ข้อควรระวัง

  • เนื่องจากคีย์ถูก lowercase อัตโนมัติ strDict["A"] และ strDict["a"] จึงหมายถึงคีย์เดียวกัน
  • StringDictionary ถือว่าเป็น legacy class - ในโค้ดใหม่ ควรใช้ Dictionary<string, string> แทน ซึ่งมีประสิทธิภาพดีกว่า type-safe และไม่บังคับ lowercase
  • อยู่ใน namespace System.Collections.Specialized

เปรียบเทียบ StringDictionary vs Dictionary<string, string>

คุณสมบัติStringDictionaryDictionary<string, string>
Key case sensitivityCase-insensitive (lowercase)Case-sensitive (default)
Type safetystring onlyGeneric, any type
Performanceช้ากว่าเร็วกว่า
NamespaceSystem.Collections.SpecializedSystem.Collections.Generic
สถานะLegacyแนะนำให้ใช้