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

วิธีลบออบเจ็กต์ครั้งแรกที่พบใน Collection ใน C#

บทความนี้สาธิตวิธีการลบออบเจ็กต์ครั้งแรกที่พบใน Collection<T> โดยใช้ method Remove(T item)

ตัวอย่างที่ 1: ลบ "Nathan" ที่พบครั้งแรก

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("Andy");
        col.Add("Kevin");
        col.Add("John");
        col.Add("Nathan");
        col.Add("Nathan");
        col.Add("Katie");
        col.Add("Barry");
        col.Add("Nathan");
        col.Add("Mark");

        Console.WriteLine("Count of elements = " + col.Count);
        Console.WriteLine("Iterating through the collection...");
        foreach (string item in col)
        {
            Console.WriteLine(item);
        }

        col.Remove("Nathan");

        Console.WriteLine("Count of elements (updated) = " + col.Count);
        Console.WriteLine("Iterating through the collection... (updated)");
        foreach (string item in col)
        {
            Console.WriteLine(item);
        }
    }
}

ผลลัพธ์

Count of elements = 9
Iterating through the collection...
Andy
Kevin
John
Nathan
Nathan
Katie
Barry
Nathan
Mark
Count of elements (updated) = 8
Iterating through the collection... (updated)
Andy
Kevin
John
Nathan
Katie
Barry
Nathan
Mark

ตัวอย่างที่ 2: ลบ "Two" ที่ซ้ำกันหลายครั้ง

using System;
using System.Collections.ObjectModel;

public class Demo
{
    public static void Main()
    {
        Collection<string> col = new Collection<string>();
        col.Add("One");
        col.Add("Two");
        col.Add("Two");
        col.Add("Four");
        col.Add("Five");
        col.Add("Two");
        col.Add("Six");
        col.Add("Seven");

        Console.WriteLine("Count of elements = " + col.Count);
        Console.WriteLine("Iterating through the collection...");
        foreach (string item in col)
        {
            Console.WriteLine(item);
        }

        col.Remove("Two");

        Console.WriteLine("Count of elements = " + col.Count);
        Console.WriteLine("Iterating through the collection... (updated)");
        foreach (string item in col)
        {
            Console.WriteLine(item);
        }
    }
}

ผลลัพธ์

Count of elements = 8
Iterating through the collection...
One
Two
Two
Four
Five
Two
Six
Seven
Count of elements = 7
Iterating through the collection... (updated)
One
Two
Four
Five
Two
Six
Seven

คำอธิบายเพิ่มเติม

  • Collection<T> เป็น base class สำหรับ collection แบบ generic ที่ปรับแต่งได้
  • Remove(T item) ลบรายการแรกที่ตรงกับค่าที่ระบุ คืนค่า bool
  • ใช้ equality comparer เริ่มต้นของ T ในการเปรียบเทียบ
  • เวลา complexity: O(n) - ต้องค้นหา linear
  • ต่างจาก List<T>: Collection<T> มี virtual methods ที่ override ได้สำหรับ custom behavior