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

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

Giới thiệu

Để lấy chỉ số (index) của một khóa cụ thể trong SortedList, bạn sử dụng phương thức IndexOfKey(object key). Phương thức trả về chỉ số dựa trên thứ tự sắp xếp của khóa, hoặc -1 nếu khóa không tồn tại.

Ví dụ 1

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"));
    }
}

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

Ví dụ 2: Hai SortedList

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"));

        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
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

Lưu ý: Chỉ số phản ánh vị trí trong thứ tự đã sắp xếp. Nếu khóa không tồn tại, phương thức trả về -1.