บทความนี้สาธิตวิธีการลบสมาชิกทั้งหมดจาก Collection<T> โดยใช้ method Clear()
ตัวอย่างที่ 1: ล้าง Collection<int>
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection<int> col = new Collection<int>();
col.Add(10);
col.Add(20);
col.Add(30);
col.Add(40);
col.Add(50);
col.Add(60);
col.Add(70);
col.Add(80);
Console.WriteLine("Elements in the Collection...");
foreach (int val in col)
{
Console.WriteLine(val);
}
Console.WriteLine("Does the collection has the element 70? = " + col.Contains(70));
Console.WriteLine("Count of elements = " + col.Count);
col.Clear();
Console.WriteLine("Count of elements (updated) = " + col.Count);
}
}
ผลลัพธ์
Elements in the Collection... 10 20 30 40 50 60 70 80 Does the collection has the element 70? = True Count of elements = 8 Count of elements (updated) = 0
ตัวอย่างที่ 2: ล้าง Collection<string>
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection<string> col = new Collection<string>();
col.Add("A");
col.Add("B");
col.Add("C");
col.Add("D");
col.Add("E");
Console.WriteLine("Elements in the Collection...");
foreach (string val in col)
{
Console.WriteLine(val);
}
Console.WriteLine("Does the collection has the element D? = " + col.Contains("D"));
Console.WriteLine("Count of elements = " + col.Count);
col.Clear();
Console.WriteLine("Count of elements (updated) = " + col.Count);
}
}
ผลลัพธ์
Elements in the Collection... A B C D E Does the collection has the element D? = True Count of elements = 5 Count of elements (updated) = 0
คำอธิบายเพิ่มเติม
Collection<T>เป็น base class สำหรับสร้าง custom collection (ใน namespace System.Collections.ObjectModel)Clear()ลบรายการทั้งหมด ทำให้ Count = 0- ความจุ (capacity) อาจคงอยู่ ขึ้นกับ implementation
Contains(T item)ตรวจสอบว่ามีรายการหรือไม่ ใช้ equality comparer เริ่มต้นของ T- เวลา complexity: O(n) - ต้องล้าง reference ทีละตัว
- Collection<T> มี virtual methods:
InsertItem,SetItem,RemoveItem,ClearItemsที่ override ได้เพื่อ custom behavior