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

Lấy giá trị tại chỉ mục cụ thể của SortedList trong C#

Giới thiệu

SortedList hỗ trợ truy cập giá trị bằng chỉ mục (index) thông qua phương thức GetByIndex(int index). Chỉ mục dựa trên thứ tự khóa đã sắp xếp (0-based). Cũng có GetKey(index) để lấy khóa tại chỉ mục.

Ví dụ 1: Lấy giá trị tại các chỉ mục

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        SortedList list = new SortedList();
        list.Add("A", "Jacob");
        list.Add("B", "Sam");
        list.Add("C", "Tom");
        list.Add("D", "John");
        list.Add("E", "Tim");
        list.Add("F", "Mark");
        list.Add("G", "Gary");
        
        Console.WriteLine("Value at index 2 = " + list.GetByIndex(2));
        Console.WriteLine("Value at index 5 = " + list.GetByIndex(5));
        Console.WriteLine("Value at index 6 = " + list.GetByIndex(6));
    }
}

Kết quả

Value at index 2 = Tom
Value at index 5 = Mark
Value at index 6 = Gary

Ví dụ 2: Lấy giá trị tại chỉ mục 0

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        SortedList list = new SortedList();
        list.Add(1, "One");
        list.Add(2, "Two");
        list.Add(3, "Three");
        list.Add(4, "Four");
        list.Add(5, "Five");
        
        Console.WriteLine("Value at index 0 = " + list.GetByIndex(0));
    }
}

Kết quả

Value at index 0 = One

Các phương thức truy cập bằng chỉ mục

Phương thức Trả về Mô tả
GetByIndex(index) object (giá trị) Giá trị tại chỉ mục
GetKey(index) object (khóa) Khóa tại chỉ mục
IndexOfKey(key) int Chỉ mục của khóa (-1 nếu không có)
IndexOfValue(value) int Chỉ mục đầu tiên của giá trị (-1 nếu không có)

Ví dụ dùng IndexOfKey/IndexOfValue

SortedList list = new SortedList();
list.Add("C", "Charlie");
list.Add("A", "Alpha");
list.Add("B", "Beta");
// Sắp xếp: A, B, C

Console.WriteLine(list.GetKey(0));    // A
Console.WriteLine(list.GetByIndex(0)); // Alpha
Console.WriteLine(list.IndexOfKey("B"));    // 1
Console.WriteLine(list.IndexOfValue("Beta")); // 1

Lưu ý

  • Chỉ mục ngoài phạm vi [0, Count-1] → ArgumentOutOfRangeException
  • Trả về object (non-generic), cần cast
  • Generic SortedList<TKey, TValue> dùng indexer list.Keys[index], list.Values[index]