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

Lấy enumerator duyệt qua SortedDictionary trong C#

SortedDictionary<TKey, TValue> là một từ điển tự động sắp xếp các khóa theo thứ tự tăng dần. Để duyệt qua các cặp key-value, bạn có thể sử dụng phương thức GetEnumerator() trả về IDictionaryEnumerator hoặc dùng foreach trực tiếp.

Ví dụ 1: Sử dụng IDictionaryEnumerator

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
        sortedDict.Add(100, "Mobile");
        sortedDict.Add(200, "Laptop");
        sortedDict.Add(300, "Desktop");
        sortedDict.Add(400, "Speakers");
        sortedDict.Add(500, "Headphone");
        sortedDict.Add(600, "Earphone");

        Console.WriteLine("Các cặp key-value của SortedDictionary...");
        
        // Lấy enumerator
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        
        // Duyệt qua enumerator
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

Kết quả

Các cặp key-value của SortedDictionary...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

Ví dụ 2: SortedDictionary<int, int> với nhiều phần tử

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedDictionary<int, int> sortedDict = new SortedDictionary<int, int>();
        sortedDict.Add(100, 1);
        sortedDict.Add(200, 2);
        sortedDict.Add(300, 3);
        sortedDict.Add(400, 4);
        sortedDict.Add(500, 5);
        sortedDict.Add(600, 6);
        sortedDict.Add(700, 7);
        sortedDict.Add(800, 8);
        sortedDict.Add(900, 9);
        sortedDict.Add(1000, 10);

        Console.WriteLine("Các cặp key-value của SortedDictionary...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

Kết quả

Các cặp key-value của SortedDictionary...
Key = 100, Value = 1
Key = 200, Value = 2
Key = 300, Value = 3
Key = 400, Value = 4
Key = 500, Value = 5
Key = 600, Value = 6
Key = 700, Value = 7
Key = 800, Value = 8
Key = 900, Value = 9
Key = 1000, Value = 10

Cách hiện đại hơn: Sử dụng foreach

Kể từ C# 5.0, khuyến nghị dùng foreach thay vì enumerator thủ công:

// Cách 1: Duyệt KeyValuePair
foreach (KeyValuePair<int, string> kvp in sortedDict)
{
    Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}

// Cách 2: Deconstruction (C# 7.0+)
foreach (var (key, value) in sortedDict)
{
    Console.WriteLine($"Key = {key}, Value = {value}");
}

// Cách 3: Chỉ lấy keys hoặc values
foreach (var key in sortedDict.Keys) { ... }
foreach (var value in sortedDict.Values) { ... }

Đặc điểm của SortedDictionary

Đặc điểm Mô tả
Sắp xếp Tự động sắp xếp key tăng dần (IComparable<TKey>)
Phức tạp truy xuất O(log n) cho Get, Add, Remove
Key trùng lặp Không cho phép
Null key Cho phép nếu TKey là reference type

Lưu ý

  • IDictionaryEnumerator là interface cũ, ít dùng trong code hiện đại
  • SortedDictionary dùng cây đỏ-đen (Red-Black Tree) nội bộ
  • Nếu cần truy xuất theo index, hãy dùng SortedList