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

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

Giới thiệu

HybridDictionary (trong namespace System.Collections.Specialized) là một từ điển kết hợp hiệu suất của ListDictionary (cho số lượng phần tử nhỏ) và Hashtable (cho số lượng lớn). Nó tự động chuyển đổi giữa hai cấu trúc này.

Ví dụ 1: Lấy giá trị theo khóa

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        HybridDictionary myDict = new HybridDictionary();
        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");
        
        Console.WriteLine("Value at key 5 = " + myDict["5"]);
    }
}

Kết quả

Value at 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()
    {
        HybridDictionary myDict = new HybridDictionary();
        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");
        
        Console.WriteLine("Value at key 5 = " + myDict["5"]);
        myDict["5"] = "Smart Watches";
        Console.WriteLine("Value at key 5 [UPDATED] = " + myDict["5"]);
    }
}

Kết quả

Value at key 5 = Notebook
Value at key 5 [UPDATED] = Smart Watches

Ví dụ 3: Sử dụng Queue (minh họa bổ sung)

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Queue queue = new Queue();
        queue.Enqueue(100);
        queue.Enqueue(200);
        queue.Enqueue(300);
        queue.Enqueue(400);
        queue.Enqueue(500);
        
        Console.WriteLine("Queue...");
        foreach (Object ob in queue)
        {
            Console.WriteLine(ob);
        }
        
        Console.WriteLine("Count of elements = " + queue.Count);
        Console.WriteLine("Synchronize access...");
        
        lock (queue.SyncRoot)
        {
            foreach (Object ob in queue)
            {
                Console.WriteLine(ob);
            }
        }
    }
}

Kết quả

Queue...
100
200
300
400
500
Count of elements = 5
Synchronize access...
100
200
300
400
500

Đặc điểm của HybridDictionary

  • Tối ưu cho cả danh sách nhỏ và lớn
  • Khóa không phân biệt chữ hoa/thường theo mặc định (case-insensitive)
  • Cho phép khóa null
  • Không đảm bảo thứ tự các phần tử