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

Interface SortedMap trong C# - SortedList

Trong Java có SortedMap, tương đương trong C# là SortedList<TKey, TValue> (namespace System.Collections.Generic) hoặc SortedList non-generic (namespace System.Collections).

SortedList là cấu trúc dữ liệu kết hợp mảng và bảng băm: truy xuất bằng key như Hashtable, truy xuất bằng index như ArrayList. Các phần tử luôn được sắp xếp theo key.

Ví dụ minh họa

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Generic SortedList - khuyến nghị dùng
        var sortedList = new SortedList();
        sortedList.Add("ST0", "One");
        sortedList.Add("ST1", "Two");
        sortedList.Add("ST2", "Three");

        Console.WriteLine("Các key (đã sắp xếp):");
        foreach (string key in sortedList.Keys)
        {
            Console.WriteLine(key);
        }

        Console.WriteLine("\nTruy xuất bằng key:");
        Console.WriteLine(sortedList["ST1"]); // Two

        Console.WriteLine("\nTruy xuất bằng index:");
        Console.WriteLine(sortedList.Values[1]); // Two
    }
}

Kết quả đầu ra

Các key (đã sắp xếp):
ST0
ST1
ST2

Truy xuất bằng key:
Two
Truy xuất bằng index:
Two

Đặc điểm: Thao tác thêm/xóa O(n) do phải dịch chuyển mảng. Phù hợp khi đọc nhiều, ghi ít.