บทความนี้สาธิตวิธีการตรวจสอบว่ามีสตริงที่ระบุอยู่ใน StringCollection หรือไม่ โดยใช้ method Contains(string value)
ตัวอย่างที่ 1: ค้นหาค่าที่ไม่มีอยู่
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
ตัวอย่างที่ 2: ค้นหาค่าที่มีอยู่
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "John", "Tim", "Kevin", "Bradman", "Katie", "Tom", "Nathan" };
Console.WriteLine("String 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("Katie"));
}
}
ผลลัพธ์
String array elements... John Tim Kevin Bradman Katie Tom Nathan Does the specified string is in the StringCollection? = True
คำอธิบายเพิ่มเติม
Contains(string value)คืนค่าtrueถ้าพบค่าที่ระบุ,falseถ้าไม่พบ- การเปรียบเทียบเป็น case-sensitive (แยกตัวพิมพ์ใหญ่เล็ก)
- เวลา complexity: O(n) - ต้องค้นหาแบบ linear ทีละตัว
- ใช้
AddRange(string[])เพิ่มข้อมูลจากอาร์เรย์ได้ทีละหลายค่า - StringCollection เป็น legacy class - สำหรับโค้ดใหม่แนะนำใช้
List<string>แทน - List<string> มี Contains เหมือนกัน แต่มี method เพิ่มเติมมากกว่า (Find, FindAll, Exists, TrueForAll, etc.)