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

Cách tạo OrderedDictionary trong C#

OrderedDictionary (trong namespace System.Collections.Specialized) lưu trữ cặp khóa/giá trị và duy trì thứ tự thêm vào. Bạn có thể truy xuất bằng khóa hoặc chỉ số.

Ví dụ 1: Thêm, duyệt và xóa phần tử

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

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

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

        Console.WriteLine("Số lượng phần tử = " + dict.Count);

        dict.Remove("E");
        Console.WriteLine("Số lượng sau khi xóa = " + dict.Count);
    }
}

Kết quả

Các phần tử OrderedDictionary...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Số lượng phần tử = 6
Số lượng sau khi xóa = 5

Ví dụ 2: Lấy danh sách khóa

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

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

        ICollection col = dict.Keys;
        String[] strKeys = new String[dict.Count];
        col.CopyTo(strKeys, 0);

        Console.WriteLine("Hiển thị các khóa...");
        for (int i = 0; i < dict.Count; i++)
        {
            Console.WriteLine(strKeys[i]);
        }
    }
}

Kết quả

Hiển thị các khóa...
1
2
3
4
5
6
7
8