Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ดึงค่าที่ดัชนีที่ระบุของ SortedList ใน C#

ภาพรวม

เมธอด SortedList.GetByIndex(int index) คืนค่าที่ดัชนีที่ระบุ (0-based) ตามลำดับที่เรียงของคีย์ ใช้เมื่อต้องการเข้าถึงค่าผ่านตำแหน่งแทนคีย์

ตัวอย่างที่ 1: ดึงค่าที่ดัชนี 2, 5, 6

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

ผลลัพธ์

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

ตัวอย่างที่ 2: ดึงค่าที่ดัชนี 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));
    }
}

ผลลัพธ์

Value at index 0 = One

คำอธิบายเพิ่มเติม

  • ดัชนี 0 ถึง Count-1 ตามลำดับคีย์ที่เรียงแล้ว
  • เข้าถึงนอกช่วงโยน ArgumentOutOfRangeException
  • เมธอดที่เกี่ยวข้อง: GetKey(int index) ดึงคีย์ที่ดัชนี, IndexOfKey(), IndexOfValue()
  • GetByIndex() เร็วกว่าการวนลูปหาค่า (O(1) vs O(n))
  • SortedList ใช้สองอาร์เรย์ภายใน (keys[], values[]) ขนาดเท่ากัน