Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xóa lần xuất hiện đầu tiên của đối tượng từ Collection trong C#

Giới thiệu

Để xóa lần xuất hiện đầu tiên của một đối tượng trong Collection<T> (từ namespace System.Collections.ObjectModel), bạn sử dụng phương thức Remove(T). Phương thức này xóa phần tử khớp đầu tiên tìm thấy.

Ví dụ 1: Xóa "Nathan" xuất hiện nhiều lần

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("Số lượng phần tử = " + col.Count);
        Console.WriteLine("Duyệt qua collection...");
        foreach (string item in col)
            Console.WriteLine(item);

        col.Remove("Nathan");

        Console.WriteLine("Số lượng phần tử (đã cập nhật) = " + col.Count);
        Console.WriteLine("Duyệt qua collection... (đã cập nhật)");
        foreach (string item in col)
            Console.WriteLine(item);
    }
}

Kết quả

Số lượng phần tử = 9
Duyệt qua collection...
Andy
Kevin
John
Nathan
Nathan
Katie
Barry
Nathan
Mark
Số lượng phần tử (đã cập nhật) = 8
Duyệt qua collection... (đã cập nhật)
Andy
Kevin
John
Nathan
Katie
Barry
Nathan
Mark

Ví dụ 2: Xóa "Two" xuất hiện nhiều lần

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("Số lượng phần tử = " + col.Count);
        Console.WriteLine("Duyệt qua collection...");
        foreach (string item in col)
            Console.WriteLine(item);

        col.Remove("Two");

        Console.WriteLine("Số lượng phần tử = " + col.Count);
        Console.WriteLine("Duyệt qua collection... (đã cập nhật)");
        foreach (string item in col)
            Console.WriteLine(item);
    }
}

Kết quả

Số lượng phần tử = 8
Duyệt qua collection...
One
Two
Two
Four
Five
Two
Six
Seven
Số lượng phần tử = 7
Duyệt qua collection... (đã cập nhật)
One
Two
Four
Five
Two
Six
Seven

Lưu ý: Collection<T> là lớp cơ sở cho các collection tùy chỉnh, hỗ trợ thêm, xóa, chèn và duyệt phần tử.