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

ดึงหรือตั้งค่าองค์ประกอบที่ดัชนีที่ระบุใน Collection ใน C#

ภาพรวม

Collection<T> ใน namespace System.Collections.ObjectModel รองรับการเข้าถึงด้วยดัชนี col[index] สำหรับทั้งการอ่านและเขียน เป็นคลาสฐานสำหรับคอลเลกชันกำหนดเอง

ตัวอย่างที่ 1: อ่านค่าที่ดัชนี 3 และ 4

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("Laptop");
        col.Add("Desktop");
        col.Add("Notebook");
        col.Add("Ultrabook");
        col.Add("Tablet");
        col.Add("Headphone");
        col.Add("Speaker");
        Console.WriteLine("Elements in Collection...");
        foreach(string str in col)
        {
            Console.WriteLine(str);
        }
        Console.WriteLine("Element at index 3 = " + col[3]);
        Console.WriteLine("Element at index 4 = " + col[4]);
    }
}

ผลลัพธ์

Elements in Collection...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 3 = Ultrabook
Element at index 4 = Tablet

ตัวอย่างที่ 2: อ่านและอัปเดตค่าที่ดัชนี 3

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("Laptop");
        col.Add("Desktop");
        col.Add("Notebook");
        col.Add("Ultrabook");
        col.Add("Tablet");
        col.Add("Headphone");
        col.Add("Speaker");
        Console.WriteLine("Elements in Collection...");
        foreach(string str in col)
        {
            Console.WriteLine(str);
        }
        Console.WriteLine("Element at index 3 = " + col[3]);
        col[3] = "SSD";
        Console.WriteLine("Element at index 3 (Updated) = " + col[3]);
    }
}

ผลลัพธ์

Elements in Collection...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 3 = Ultrabook
Element at index 3 (Updated) = SSD

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

  • Collection<T> ให้การเข้าถึงดัชนี O(1) เหมือน List
  • เหมาะสำหรับสร้างคอลเลกชันเฉพาะเจาะจงโดยการสืบทอด (inherit) และ override เมธอดเสมือน (virtual) เช่น InsertItem, SetItem, RemoveItem, ClearItems
  • ดัชนีต้องอยู่ในช่วง 0 ถึง Count-1
  • ไม่มี Capacity property แยกต่างหาก ขนาดภายในจัดการอัตโนมัติ