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

Lấy hoặc đặt giá trị tại khóa cụ thể trong StringDictionary C#

Giới thiệu

StringDictionary (namespace System.Collections.Specialized) là một từ điển được tối ưu hóa cho các khóa và giá trị đều là chuỗi (string). Nó tự động chuyển khóa thành chữ thường (case-insensitive).

Ví dụ 1: Lấy 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", "SSD");
        myDict.Add("9", "Headphone");
        myDict.Add("10", "Earphone");
        
        Console.WriteLine("Value for key 5 = " + myDict["5"]);
    }
}

Kết quả

Value for key 5 = Notebook

Ví dụ 2: Cập nhậ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", "SSD");
        myDict.Add("9", "Headphone");
        myDict.Add("10", "Earphone");
        
        Console.WriteLine("Value for key 5 = " + myDict["5"]);
        myDict["5"] = "Flash Drive";
        Console.WriteLine("Value for key 5 [Updated] = " + myDict["5"]);
    }
}

Kết quả

Value for key 5 = Notebook
Value for key 5 [Updated] = Flash Drive

Đặc điểm quan trọng của StringDictionary

  • Khóa và giá trị đều phải là string
  • Khóa không phân biệt chữ hoa/thường (luôn được lưu dưới dạng chữ thường)
  • Không cho phép khóa null
  • Thứ tự phần tử không được bảo toàn
  • Hiệu suất tốt cho việc tra cứu chuỗi

So sánh với HybridDictionary

Đặc điểm StringDictionary HybridDictionary
Kiểu khóa/giá trị Chỉ string object (bất kỳ)
Khóa null Không cho phép Cho phép
Case-sensitive Không (luôn lower) Cấu hình được