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

Tạo ListDictionary trong C#

Giới thiệu

ListDictionary (namespace System.Collections.Specialized) là từ điển đơn giản dựa trên **danh sách liên kết đơn** (singly linked list). Phù hợp cho **số lượng phần tử nhỏ** (thường < 10). Không generic, key/value là object.

Đặc điểm

  • Tìm kiếm O(n) - chậm hơn Dictionary (O(1)) khi n lớn.
  • Bộ nhớ ít hơn cho collection nhỏ.
  • Key **không phân biệt chữ hoa/thường** (case-insensitive) mặc định.
  • Cho phép key trùng lặp? **Không** (giống Dictionary).

Ví dụ 1: Tạo, thêm, duyệt, kiểm tra thuộc tính

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

public class Demo
{
    public static void Main()
    {
        ListDictionary dict = new ListDictionary();
        dict.Add("1", "SUV");
        dict.Add("2", "Sedan");
        dict.Add("3", "Utility Vehicle");
        dict.Add("4", "Compact Car");
        dict.Add("5", "SUV");
        dict.Add("6", "Sedan");
        dict.Add("7", "Utility Vehicle");
        dict.Add("8", "Compact Car");
        dict.Add("9", "Crossover");
        dict.Add("10", "Electric Car");

        Console.WriteLine("ListDictionary elements:");
        foreach (DictionaryEntry entry in dict)
        {
            Console.WriteLine($"{entry.Key} {entry.Value}");
        }

        Console.WriteLine($"\nIsFixedSize: {dict.IsFixedSize}");
        Console.WriteLine($"IsReadOnly: {dict.IsReadOnly}");
        Console.WriteLine($"IsSynchronized: {dict.IsSynchronized}");
        Console.WriteLine($"Contains key 'K': {dict.Contains("K")}");
        Console.WriteLine($"Contains key '9': {dict.Contains("9")}");
    }
}

Kết quả

ListDictionary elements:
1 SUV
2 Sedan
3 Utility Vehicle
4 Compact Car
5 SUV
6 Sedan
7 Utility Vehicle
8 Compact Car
9 Crossover
10 Electric Car

IsFixedSize: False
IsReadOnly: False
IsSynchronized: False
Contains key 'K': False
Contains key '9': True

Ví dụ 2: Nhiều Dictionary, gán tham chiếu, Clear

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

public class Demo
{
    public static void Main()
    {
        ListDictionary dict1 = new ListDictionary();
        dict1.Add("A", "Books");
        dict1.Add("B", "Electronics");
        dict1.Add("C", "Smart Wearables");
        dict1.Add("D", "Pet Supplies");
        dict1.Add("E", "Clothing");
        dict1.Add("F", "Footwear");

        Console.WriteLine("Dict1:");
        foreach (DictionaryEntry d in dict1) Console.WriteLine($"{d.Key} {d.Value}");
        Console.WriteLine($"Count: {dict1.Count}");

        ListDictionary dict2 = new ListDictionary();
        dict2.Add("1", "One");
        dict2.Add("2", "Two");
        dict2.Add("3", "Three");
        dict2.Add("4", "Four");
        dict2.Add("5", "Five");
        dict2.Add("6", "Six");

        Console.WriteLine("\nDict2:");
        foreach (DictionaryEntry d in dict2) Console.WriteLine($"{d.Key} {d.Value}");
        Console.WriteLine($"Count: {dict2.Count}");

        // Gán tham chiếu (không copy)
        ListDictionary dict3 = dict2;
        Console.WriteLine($"\ndict3 == dict2? {dict3.Equals(dict2)}"); // True (same reference)

        dict3.Clear();
        Console.WriteLine($"Dict2 Count sau dict3.Clear(): {dict2.Count}"); // 0 !!
        Console.WriteLine($"Dict3 Count: {dict3.Count}"); // 0
    }
}

Kết quả

Dict1:
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Count: 6

Dict2:
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Count: 6

dict3 == dict2? True
Dict2 Count sau dict3.Clear(): 0
Dict3 Count: 0

⚠️ Cảnh quan trọng

ListDictionary dict3 = dict2; chỉ gán **tham chiếu**, không tạo bản sao. dict3.Clear() làm rỗng cả dict2.

So sánh với Dictionary<string, string>

Đặc điểmListDictionaryDictionary<string,string>
Cấu trúc dữ liệuLinked listHash table
Hiệu năng tìm kiếmO(n)O(1)
Phù hợp< 10 phần tửMọi kích thước
GenericKhôngCó
Key case-sensitiveKhông (mặc định)Có (mặc định)

Khuyến nghị

  • **Không dùng ListDictionary** cho code mới. Dùng Dictionary<string, string> hoặc ConcurrentDictionary.
  • Chỉ gặp trong legacy code (.NET 1.x/2.0).