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

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


ในการรับหรือตั้งค่าองค์ประกอบที่ดัชนีที่ระบุในคอลเลกชัน รหัสจะเป็นดังนี้ -

ตัวอย่าง

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

ตัวอย่าง

เรามาดูตัวอย่างกัน −

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