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

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

ภาพรวม

StringCollection รองรับการเข้าถึงองค์ประกอบผ่านดัชนี (indexer) แบบอ่าน/เขียนได้ คล้าย List แต่เฉพาะสำหรับสตริง

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

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
        Console.WriteLine("StringCollection elements...");
        foreach (string str in strArr)
        {
            Console.WriteLine(str);
        }
        strCol.AddRange(strArr);
        Console.WriteLine("Element at 5th index = " + strCol[5]);
        Console.WriteLine("Count of strings in StringCollection = " + strCol.Count);
    }
}

ผลลัพธ์

StringCollection elements...
A
B
C
D
E
F
G
H
Element at 5th index = F
Count of strings in StringCollection = 8

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

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
        Console.WriteLine("StringCollection elements...");
        foreach (string str in strArr)
        {
            Console.WriteLine(str);
        }
        strCol.AddRange(strArr);
        Console.WriteLine("Element at 5th index = " + strCol[5]);
        strCol[5] = "K";
        Console.WriteLine("Element at 5th index [UPDATED] = " + strCol[5]);
    }
}

ผลลัพธ์

StringCollection elements...
A
B
C
D
E
F
G
H
Element at 5th index = F
Element at 5th index [UPDATED] = K

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

  • ดัชนีเริ่มต้นที่ 0 ดังนั้น "5th index" หมายถึงองค์ประกอบที่ 6 (F)
  • StringCollection ไม่มีเมธอด Insert หรือ RemoveAt ต้องใช้ Add, Remove, Clear แทน
  • การ set ค่าที่ดัชนีจะแทนที่สตริงเดิม ต้องแน่ใจว่าดัชนีอยู่ในช่วงที่ถูกต้อง
  • คลาสนี้เป็น legacy สำหรับโค้ดใหม่แนะนำ List<string>