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

Lấy khóa tại chỉ số chỉ định của SortedList trong C#

Giới thiệu

SortedList lưu trữ cặp khóa/giá trị được sắp xếp theo khóa. Để lấy khóa tại một chỉ số cụ thể, sử dụng phương thức GetKey(int index). Để tìm chỉ số của một khóa, sử dụng IndexOfKey(object key).

Ví dụ 1: SortedList với khóa chuỗi, giá trị số

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        SortedList list1 = new SortedList();
        list1.Add("One", 1);
        list1.Add("Two ", 2);
        list1.Add("Three ", 3);
        list1.Add("Four", 4);
        list1.Add("Five", 5);
        list1.Add("Six", 6);
        list1.Add("Seven ", 7);
        list1.Add("Eight ", 8);
        list1.Add("Nine", 9);
        list1.Add("Ten", 10);

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

        Console.Write("Chỉ số tại khóa Five = " + list1.IndexOfKey("Five"));
        Console.Write("\nKhóa tại chỉ số 2 = " + list1.GetKey(2));

        SortedList list2 = new SortedList();
        list2.Add("A", "Accessories");
        list2.Add("B", "Books");
        list2.Add("C", "Smart Wearable Tech");
        list2.Add("D", "Home Appliances");

        Console.WriteLine("\n\nCác phần tử của SortedList2...");
        foreach (DictionaryEntry d in list2)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }
        Console.Write("Chỉ số tại khóa B = " + list2.IndexOfKey("B"));
    }
}

Kết quả

Các phần tử của SortedList1...
Eight   8
Five    5
Four    4
Nine    9
One     1
Seven   7
Six     6
Ten     10
Three   3
Two     2
Chỉ số tại khóa Five = 1
Khóa tại chỉ số 2 = Four
Các phần tử của SortedList2...
A Accessories
B Books
C Smart Wearable Tech
D Home Appliances
Chỉ số tại khóa B = 1

Ví dụ 2: SortedList với khóa và giá trị đều là chuỗi

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ử của SortedList...");
        foreach (DictionaryEntry d in list)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("\nChỉ số tại khóa One = " + list.IndexOfKey("One"));
        Console.Write("\nKhóa tại chỉ số 5 = " + list.GetKey(5));
    }
}

Kết quả

Các phần tử của SortedList...
Five Operations
Four Purchase
One Finance
Six IT
Three Sales
Two Marketing
Chỉ số tại khóa One = 2
Khóa tại chỉ số 5 = Two

Lưu ý: SortedList sắp xếp theo khóa. Chỉ số dựa trên thứ tự đã sắp xếp, không phải thứ tự thêm vào. Khóa không được trùng lặp.