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

Kiểm tra SortedList có kích thước cố định trong C#

Thuộc tính IsFixedSize của SortedList luôn trả về false vì SortedList có thể thay đổi kích thước (thêm/xóa phần tử).

Ví dụ 1: Kiểm tra IsFixedSize và ContainsValue

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        SortedList list = new SortedList();
        list.Add("1", "One");
        list.Add("2", "Two");
        list.Add("3", "Three");
        list.Add("4", "Four");
        list.Add("5", "Five");
        list.Add("6", "Six");
        list.Add("7", "Seven");
        list.Add("8", "Eight");

        Console.WriteLine("Khóa và Giá trị của SortedList....");
        foreach (DictionaryEntry k in list)
            Console.WriteLine("Khóa: {0}, Giá trị: {1}", k.Key, k.Value);

        Console.WriteLine("SortedList có giá trị 'Three'? " + list.ContainsValue("Three"));
        Console.WriteLine("SortedList có kích thước cố định? = " + list.IsFixedSize);
    }
}

Kết quả

Khóa và Giá trị của SortedList....
Khóa: 1, Giá trị: One
Khóa: 2, Giá trị: Two
Khóa: 3, Giá trị: Three
Khóa: 4, Giá trị: Four
Khóa: 5, Giá trị: Five
Khóa: 6, Giá trị: Six
Khóa: 7, Giá trị: Seven
Khóa: 8, Giá trị: Eight
SortedList có giá trị 'Three'? True
SortedList có kích thước cố định? = False

Ví dụ 2: SortedList khác

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        SortedList list = new SortedList();
        list.Add("1", "John");
        list.Add("2", "Tim");
        list.Add("3", "Karl");
        list.Add("4", "Gary");
        list.Add("5", "Katie");

        Console.WriteLine("Khóa và Giá trị của SortedList....");
        foreach (DictionaryEntry k in list)
            Console.WriteLine("Khóa: {0}, Giá trị: {1}", k.Key, k.Value);

        Console.WriteLine("SortedList có kích thước cố định? = " + list.IsFixedSize);
    }
}

Kết quả

Khóa và Giá trị của SortedList....
Khóa: 1, Giá trị: John
Khóa: 2, Giá trị: Tim
Khóa: 3, Giá trị: Karl
Khóa: 4, Giá trị: Gary
Khóa: 5, Giá trị: Katie
SortedList có kích thước cố định? = False