Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách tạo StringDictionary trong C#

StringDictionary (namespace System.Collections.Specialized) là một hashtable được thiết kế chuyên biệt cho khóa và giá trị đều là chuỗi. Khóa không phân biệt chữ hoa/thường (case-insensitive).

Ví dụ 1: Thêm và duyệt các phần tử

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("Các phần tử StringDictionary...");
        foreach (DictionaryEntry de in strDict)
        {
            Console.WriteLine(de.Key + " " + de.Value);
        }
    }
}

Kết quả

Các phần tử StringDictionary...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

Ví dụ 2: Truy xuất giá trị theo khóa

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("Giá trị cho khóa '5' = " + myDict["5"]);
    }
}

Kết quả

Giá trị cho khóa 5 = Notebook

Lưu ý: Khóa được tự động chuyển thành chữ thường. StringDictionary đã lỗi thời, khuyến nghị dùng Dictionary<string, string> cho mã mới.