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

การแทรกที่ดัชนีที่ระบุใน StringCollection ใน C#

ภาพรวม

StringCollection (ใน System.Collections.Specialized) เป็นคอลเลกชันสตริงแบบไดนามิก เมธอด Insert(Int32, String) แทรกสตริงที่ดัชนีที่กำหนด

ตัวอย่าง 1: แทรก 1 รายการ

using System;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringCollection strCol = new StringCollection();
        strCol.Add("Accessories");
        strCol.Add("Books");
        strCol.Add("Electronics");

        Console.WriteLine("StringCollection elements...");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }

        strCol.Insert(2, "Headphone");

        Console.WriteLine("StringCollection elements...UPDATED");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }
    }
}

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

StringCollection elements...
Accessories
Books
Electronics
StringCollection elements...UPDATED
Accessories
Books
Headphone
Electronics

ตัวอย่าง 2: แทรกหลายรายการติดต่อกัน

using System;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringCollection strCol = new StringCollection();
        strCol.Add("Laptop");
        strCol.Add("Desktop");
        strCol.Add("Tablet");
        strCol.Add("Speakers");

        Console.WriteLine("StringCollection elements...");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }

        strCol.Insert(2, "Headphone");
        strCol.Insert(3, "Alienware");

        Console.WriteLine("StringCollection elements...UPDATED");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }

        strCol.Insert(4, "E-Book Reader");
        strCol.Insert(5, "Monitor");
        strCol.Insert(6, "HDD");
        strCol.Insert(7, "SSD");

        Console.WriteLine("StringCollection elements...UPDATED");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }
    }
}

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

StringCollection elements...
Laptop
Desktop
Tablet
Speakers
StringCollection elements...UPDATED
Laptop
Desktop
Headphone
Alienware
Tablet
Speakers
StringCollection elements...UPDATED
Laptop
Desktop
Headphone
Alienware
E-Book Reader
Monitor
HDD
SSD
Tablet
Speakers

สรุป

  • Insert(index, value) – index เริ่มจาก 0
  • ดัชนีเกินขอบเขตจะโยน ArgumentOutOfRangeException
  • เหมาะสำหรับจัดการรายการสตริงที่ต้องการลำดับเฉพาะ