บทความนี้สาธิตวิธีการดึงจำนวนสตริง (strings) ใน StringCollection โดยใช้ property Count พร้อมการเข้าถึงข้อมูลด้วยดัชนี
ตัวอย่างที่ 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[] { "10", "20", "30", "40", "50" };
Console.WriteLine("StringCollection elements...");
foreach (string str in strArr)
{
Console.WriteLine(str);
}
strCol.AddRange(strArr);
Console.WriteLine("Count of strings in StringCollection = " + strCol.Count);
}
}
ผลลัพธ์
StringCollection elements... 10 20 30 40 50 Count of strings in StringCollection = 5
คำอธิบายเพิ่มเติม
StringCollection.Countคืนจำนวนสตริงใน collection เป็น int- รองรับ indexer
strCol[index]สำหรับ get/set ค่าตามดัชนี (0-based) AddRange(string[])เพิ่มอาร์เรย์ทั้งชุดได้ครั้งเดียว- StringCollection เป็น legacy class ใน namespace
System.Collections.Specialized - สำหรับโค้ดใหม่ แนะนำใช้
List<string>ซึ่งมีฟีเจอร์มากกว่า (LINQ, Find, Sort, etc.) - StringCollection ไม่ใช่ thread-safe