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

การเพิ่มสตริงไปยังท้าย StringCollection ใน C#

ภาพรวม

StringCollection (ใน System.Collections.Specialized) ให้เมธอด Add(string) เพื่อเพิ่มสตริงต่อท้ายคอลเลกชัน

ตัวอย่างที่ 1: เพิ่มชื่อหลายรายการ

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        strCol.Add("John");
        strCol.Add("Tim");
        strCol.Add("Gary");
        strCol.Add("Katie");
        strCol.Add("Andy");
        strCol.Add("Amy");
        strCol.Add("Scarlett");
        strCol.Add("Jacob");

        Console.WriteLine("Elements in StringCollection...");
        foreach (Object ob in strCol)
        {
            Console.WriteLine(ob);
        }

        Console.WriteLine("Count of elements = " + strCol.Count);
    }
}

ผลลัพธ์

Elements in StringCollection...
John
Tim
Gary
Katie
Andy
Amy
Scarlett
Jacob
Count of elements = 8

ตัวอย่างที่ 2: เพิ่มสตริงน้อยกว่า

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        strCol.Add("One");
        strCol.Add("Two");
        strCol.Add("Three");
        strCol.Add("Four");
        strCol.Add("Five");

        Console.WriteLine("Elements in StringCollection...");
        foreach (Object ob in strCol)
        {
            Console.WriteLine(ob);
        }
    }
}

ผลลัพธ์

Elements in StringCollection...
One
Two
Three
Four
Five

สรุป

  • Add เพิ่มสตริงต่อท้าย
  • มี AddRange สำหรับเพิ่มหลายค่าพร้อมกัน
  • StringCollection เป็น legacy ใหม่ควรใช้ List<string> แทน