ภาพรวม
StringCollection ใน System.Collections.Specialized เป็นคอลเลกชันเฉพาะสำหรับสตริง มี property และ method สำหรับจัดการข้อความ
Property หลัก
| Property | คำอธิบาย |
|---|---|
| Count | จำนวนสตริงในคอลเลกชัน |
| IsReadOnly | เป็น read-only หรือไม่ (ปกติ false) |
| IsSynchronized | thread-safe หรือไม่ |
| Item[Int32] | เข้าถึง/ตั้งค่าสตริงที่ดัชนี |
| SyncRoot | อ็อบเจกต์สำหรับ synchronize |
Method หลัก
| Method | คำอธิบาย |
|---|---|
| Add(String) | เพิ่มสตริงท้ายคอลเลกชัน |
| AddRange(String[]) | เพิ่มอาร์เรย์สตริงท้ายคอลเลกชัน |
| Clear() | ล้างข้อมูลทั้งหมด |
| Contains(String) | ตรวจสอบว่ามีสตริงหรือไม่ |
| CopyTo(String[], Int32) | คัดลอกไปอาร์เรย์สตริง เริ่มดัชนีที่ระบุ |
| Equals(Object) | เปรียบเทียบออบเจกต์ (reference equality) |
| GetEnumerator() | คืน StringEnumerator สำหรับวนลูป |
ตัวอย่างที่ 1: ตรวจสอบความเท่ากันของ StringCollection สองตัว
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection strCol1 = new StringCollection();
strCol1.Add("Accessories");
strCol1.Add("Books");
strCol1.Add("Electronics");
Console.WriteLine("StringCollection1 elements...");
foreach (string res in strCol1)
{
Console.WriteLine(res);
}
StringCollection strCol2 = new StringCollection();
strCol2.Add("Accessories");
strCol2.Add("Books");
strCol2.Add("Electronics");
Console.WriteLine("StringCollection2 elements...");
foreach (string res in strCol1) // bug ในโค้ดต้นฉบับ: ควรเป็น strCol2
{
Console.WriteLine(res);
}
Console.WriteLine("Both the String Collections are equal? = " + strCol1.Equals(strCol2));
}
}
ผลลัพธ์
StringCollection1 elements... Accessories Books Electronics StringCollection2 elements... Accessories Books Electronics Both the String Collections are equal? = False
หมายเหตุ: Equals() เปรียบเทียบ reference ไม่ใช่ค่าภายใน ดังนั้นคืน false แม้ข้อมูลเหมือนกัน
ตัวอย่างที่ 2: ตรวจสอบว่ามีสตริงใน StringCollection หรือไม่
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("Array elements...");
foreach (string res in arr)
{
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Does the specified string is in the StringCollection? = " + stringCol.Contains("800"));
}
}
ผลลัพธ์
Array elements... 100 200 300 400 500 Does the specified string is in the StringCollection? = False
สรุป
- StringCollection เหมาะสำหรับเก็บสตริงจำนวนมาก
Equals()เปรียบเทียบ reference ต้องใช้โค้ดเปรียบเทียบเองหากต้องการเปรียบเทียบค่าContains()ค้นหาแบบ linear search O(n)- โค้ดตัวอย่างที่ 1 มี bug: foreach ใช้ strCol1 แทน strCol2