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

การแทรกสมาชิกเข้าไปใน Collection ที่ดัชนีที่ระบุใน C#

ภาพรวม

Collection<T> (ใน System.Collections.ObjectModel) เป็นคลาสฐานสำหรับคอลเลกชันกำหนดเอง มีเมธอด Insert(Int32, T) แทรกสมาชิกที่ดัชนี

ตัวอย่าง 1: แทรกที่ดัชนี 5

using System;
using System.Collections.ObjectModel;

public class Demo {
    public static void Main() {
        Collection col = new Collection();
        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]);

        col.Insert(5, "Alienware");

        Console.WriteLine("Elements in Collection...UPDATED");
        foreach (string str in col) {
            Console.WriteLine(str);
        }
    }
}

ผลลัพธ์ตัวอย่าง 1

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

ตัวอย่าง 2: แทรกที่ดัชนี 3

using System;
using System.Collections.ObjectModel;

public class Demo {
    public static void Main() {
        Collection col = new Collection();
        col.Add("Andy");
        col.Add("Kevin");
        col.Add("John");
        col.Add("Kevin");
        col.Add("Mary");
        col.Add("Katie");
        col.Add("Barry");
        col.Add("Nathan");

        Console.WriteLine("Elements in Collection...");
        foreach (string str in col) {
            Console.WriteLine(str);
        }

        col.Insert(3, "Jacob");

        Console.WriteLine("Elements in Collection...UPDATED");
        foreach (string str in col) {
            Console.WriteLine(str);
        }
    }
}

ผลลัพธ์ตัวอย่าง 2

Elements in Collection...
Andy
Kevin
John
Kevin
Mary
Katie
Barry
Nathan
Elements in Collection...UPDATED
Andy
Kevin
John
Jacob
Kevin
Mary
Katie
Barry
Nathan

สรุป

  • Insert(index, item) – index 0-based, ต้องอยู่ในช่วง 0 ถึง Count
  • Collection<T> ให้การควบคุมพฤติกรรมได้มากกว่า List<T> (override virtual methods)
  • ใช้ใน scenario ที่ต้องการ custom collection