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

Kiểm tra SortedList chỉ đọc (read-only) trong C#

Giới thiệu

SortedList (namespace System.Collections) là mảng khóa-giá trị tự sắp xếp theo khóa. Thuộc tính IsReadOnly luôn trả về false vì nó cho phép sửa đổi.

Ví dụ 1: Kiểm tra IsReadOnly và lấy danh sách giá trị

using System;
using System.Collections;

public class Demo
{
    public static void Main(string[] args)
    {
        SortedList list = new SortedList();
        list.Add("One", "IT");
        list.Add("Two ", "Operations");
        list.Add("Three", "Marketing");
        list.Add("Four", "Purchase");
        list.Add("Five", "Sales");
        list.Add("Six", "Finance");

        Console.WriteLine("Các phần tử SortedList...");
        foreach (DictionaryEntry d in list)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("\nDanh sách giá trị...SortedList");
        IList col = list.GetValueList();
        foreach (string res in col)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("\nSortedList chỉ đọc? = " + list.IsReadOnly);
    }
}

Kết quả

Các phần tử SortedList...
Five Sales
Four Purchase
One IT
Six Finance
Three Marketing
Two  Operations
Danh sách giá trị...SortedList
Sales
Purchase
IT
Finance
Marketing
Operations
SortedList chỉ đọc? = False

Ví dụ 2: Lấy chỉ số khóa và tập khóa

using System;
using System.Collections;

public class Demo
{
    public static void Main(string[] args)
    {
        SortedList list = new SortedList();
        list.Add("One", "Finance");
        list.Add("Two", "Marketing");
        list.Add("Three", "Sales");
        list.Add("Four", "Purchase");
        list.Add("Five", "Operations");
        list.Add("Six", "IT");

        Console.WriteLine("Các phần tử SortedList...");
        foreach (DictionaryEntry d in list)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("\nChỉ số tại khóa 'One' = " + list.IndexOfKey("One"));
        ICollection col = list.Keys;
        Console.WriteLine("\nTập hợp các khóa...");
        foreach (string res in col)
            Console.WriteLine(res);

        Console.WriteLine("\nSortedList chỉ đọc? = " + list.IsReadOnly);
    }
}

Kết quả

Các phần tử SortedList...
Five Operations
Four Purchase
One Finance
Six IT
Three Sales
Two Marketing
Chỉ số tại khóa 'One' = 2
Tập hợp các khóa...
Five
Four
One
Six
Three
Two
SortedList chỉ đọc? = False

Chú ý

  • SortedList dùng mảng nội bộ, truy xuất theo index O(1), thêm/xóa O(n) do phải dịch chuyển.
  • GetValueList() và GetKeyList() trả về view (IList) chỉ đọc nhưng không phải bản sao.
  • Generic version: SortedList<TKey, TValue> trong System.Collections.Generic.